It's my understanding that copy-on-write for std::string
is no longer present with C++11.
The following code would demonstrate that this isn't completely true.
#include <string>
#include <iostream>
void Modify(std::string& s)
{
if (!s.empty())
{
*const_cast<char*>(s.data()) = 'W';
}
}
int main()
{
std::string a = "Hello World";
std::string b = a; // Does not do a deep copy.
Modify(a);
std::cout << (a == b ? "Failed\n" : "Succeeded\n");
return 0;
}
I'm not sure what rule I'm breaking here.
Whatever about casting const away, why isn't the deep copy done?
I know it can be forced with std::string b = a.c_str();
but that's not the point.
g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2