std::string::reserve()

Neil Ferguson nferguso@eso.org
Thu Feb 12 15:27:00 GMT 2004


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.



More information about the Libstdc++ mailing list