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

时间:2013-05-17 08:44:00

标签: c++ gcc copy-constructor deep-copy stdstring

我想知道我是否误解了某些内容:来自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!!");

这将打印出“你很快就会进入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!");

将内容复制到新字符串中。

2 个答案:

答案 0 :(得分:14)

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

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

答案 1 :(得分: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.

这是关于引用计数字符串的3篇优秀文章。

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

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

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