http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52938

--- Comment #11 from Jonathan Wakely <redi at gcc dot gnu.org> 2012-04-12 
00:22:01 UTC ---
(In reply to comment #7)
> Don't you think this is a problem?  I called reserve on x to avoid memory
> reallocation, and yet I am faced with memory reallocation just because I call
> doit; whose signature (const ref) suggests that my object should not be
> changed.

If it didn't behave like that then you'd instead get an allocation when the
third party library copied the string.  You can't avoid the allocation
entirely, the difference is just where it happens, earlier or later.

You can always construct examples where it's apparently a problem, but I can
also show plenty of examples where that behaviour is beneficial, or even
required by the standard.

Consider:

  string s1("abc");
  s1.reserve(4);
  const string s2 = s1;
  const char* p = &s2[0];
  s1 += 'a';
  assert( p == &s2[0] );

For this to work with a reference-counted string the memory originally
allocated for s1 must still be pointed to by p, so appending to s1 must
allocate new memory.

The benefits and problems of reference-counted strings are well known and it's
not going to be changed now, std::string is stable and effectively frozen
except for serious bugs.  This isn't a bug, it's behaviour allowed by the C++
2003 standard, even if it's not the behaviour you expect or want.

Reply via email to