std :: string copy构造函数不在GCC 4.1.2中?

Phi*_*ski 13 c++ gcc deep-copy stdstring copy-constructor

我想知道我是否误解了某些内容:复制构造函数是否std::string 复制其内容?

string str1 = "Hello World";
string str2(str1);

if(str1.c_str() == str2.c_str()) // Same pointers!
  printf ("You will get into the IPC hell very soon!!");
Run Code Online (Sandbox Code Playgroud)

这将打印出"你很快就会进入IPC地狱!" 它让我烦恼

这是正常的行为std::string吗?我在某处读到它通常会做一个深层复制.

但是,这可以按预期工作:

string str3(str1.c_str());

if(str1.c_str() == str3.c_str()) // Different pointers!
  printf ("You will get into the IPC hell very soon!!");
else
  printf ("You are safe! This time!");
Run Code Online (Sandbox Code Playgroud)

它将内容复制到新字符串中.

pmr*_*pmr 14

您的string实现完全有可能使用写入时写入来解释行为.虽然对于较新的实现(并且不符合C++ 11实现),这种可能性较小.

该标准对返回的指针的值没有限制c_str(除了它指向以null结尾的c字符串),因此您的代码本质上是不可移植的.

  • @ user93353如果您想要符合C++ 11,则无法实现COW:http://stackoverflow.com/questions/12199710/legality-of-cow-stdstring-implementation-in-c11 (2认同)
  • @syam这被认为是一个缺陷,可能会改变:http://stackoverflow.com/questions/12520192/is-stdstring-refcounted-in-gcc-c11和链接的线程. (2认同)

use*_*353 5

std::string您的编译器中的实现必须被引用计数.更改其中一个字符串,然后再次检查指针 - 它们会有所不同.

string str1 = "Hello World";
string str2(str1);

if(str1.c_str() == str2.c_str()) // Same pointers!
  printf ("You will get into the IPC hell very soon!!");

str2.replace(' ',',');

// Check again here.
Run Code Online (Sandbox Code Playgroud)

这是关于参考计数字符串的3篇优秀文章.

http://www.gotw.ca/gotw/043.htm

http://www.gotw.ca/gotw/044.htm

http://www.gotw.ca/gotw/045.htm