Xcode - shallow copy in STL string assignment

When running the following C ++ code in Xcode:

std::wstring str1 = L"1111";
std::wstring str2 = str1;

void* ptr1 = (void*)str1.c_str();
void* ptr2 = (void*)str2.c_str();

      

The result is that both pointers are equal. Is this standard? This is not the case in Visual Studio.

+3


source to share


1 answer


It looks like the implementation is using a copy-on-write (COW) optimization in which the internal state of rows is really only set when a write * operation is performed . This was allowed in pre-C ++ 11 implementations, but I don't think it's a standard since C ++ 11.

Note that you can check that the address of the base pointer changes when you access the string in a non-const manner, without even writing it:

str2[0];

      

Evaluation of this expression should initiate a write operation that would change the address of the pointer. Here's a working example:

#include <string>
#include <iostream>

int main() 
{
  std::wstring str1 = L"1111";
  std::wstring str2 = str1;

  std::cout << (void*)str1.c_str() << " " << (void*)str2.c_str() << std::endl;

  str2[0]; // forces a write operation. c_str() changes.

  std::cout << (void*)str1.c_str() << " " << (void*)str2.c_str() << std::endl;
}

      



In the latest gcc, this gives

0x8a8e014 0x8a8e014
0x8a8e014 0x8a8e03c

      


* Some non-const calls can initiate writing even if they do not semantically mutate the string, as shown in the example above.

+2


source







All Articles