This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: std::string::reserve()
Neil Ferguson wrote:
What if someone does:
string s("abc");
char& c(s[1]); <--- s becomes leaked
s.reserve(); <--- no reallocation needed, so no _M_clone(), but
_M_set_sharable() before return - s "un-leaked"
string t = s; <--- s is refcopied
c = 'z'; <--- here we alter both s and t
with no reallocation taking place, the character reference is still to
a valid location, so no segfault or valgrind-type catch. Whereas if
reserve() leaves s leaked, it won't be refcopied and this stays safe.
Your line of reasoning can be applied to all the member functions and
then we have a perfectly "safe" situation that... doesn't use refcopy
at all, never!!!
I mean, seriously, have a look at 21.3 and the example therein: non-const
member functions (like reserve, or append assign, replace, etc.) *are*
supposed to invalidate references, pointers, iterators and the user cannot
safely use a reference after a reserve!
The standard is like this exactly because wants to make possible an
efficient refcopied implementation.
Paolo.