Optimal basic_string<>::append

Paolo Carlini pcarlini@unitus.it
Mon Dec 17 06:54:00 GMT 2001


Ryszard Kabatek wrote:

> So the append member function can be implemented in the way:
>
>     append(const basic_string& __str)
>     {
>       // Iff appending itself, string needs to pre-reserve the
>       // correct size so that _M_mutate does not clobber the
>       // iterators formed here.
>       if (this == &__str)
>       {
>          size_type __size = __str.size();
>          size_type __len = __size + this->size();
>          if (__len > this->capacity())
>            this->reserve(__len);
>       }
>       return _M_replace_safe(_M_iend(), _M_iend(), __str._M_ibegin(),
>                              __str._M_iend());
>     }
>
> Now append has benefit from the good reallocation strategy of _M_mutate.

Hi,

first blush, I think this is not ok. The reason is the following: if
_M_replace_safe, that is _M_mutate inside it, reallocates the string (this
happen when this != &str) and the string is not shared, the iterators __k1 and
__k2, pointing to the original memory area, becomes invalid (when a string is
reallocated because his capacity is exceeded (vs because the _Rep becomes
unshared) the original memory area is freed!)

Therefore, the comment in the code should be probably slightly changed in this
way: strings need to pre-reserve if appending themselves while being not shared.

Nathan?

Cheers,
Paolo.




More information about the Libstdc++ mailing list