This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: std::string::reserve()
Paolo Carlini wrote:
It does seem to me that previous versions of reserve() could return
with the string still in the leaked state, though, if the method
decided that no call to _M_clone() was necessary.
Indeed, but in that case you didn't pay the price of _S_create inside
_M_clone, so... probably a good trade-off: the string doesn't become
sharable but we don't spend time copying it either...
Sorry for a little bit of confusion here: what I really mean is that,
probably, irrespective of the details of your change, we should remember
to _always_ call _M_set_sharable() before leaving reserve, since this
is allowed by the standard and by definition a sharable string can be
quickly refcopied.
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.
Neil.