std::string复制构造函数在GCC 4.1.2中不深入

std::string copy constructor NOT deep in GCC 4.1.2?

本文关键字:GCC 复制 string 构造函数 std      更新时间:2023-10-16

我想知道我是否误解了一些东西:从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!!");

这会打印"You will get into the IPC hell very soon!!",这让我很恼火。

这是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!");

将内容复制到新字符串中

您的string实现完全有可能使用写时复制,这将解释该行为。尽管这在较新的实现(以及c++ 11实现的不一致性)中不太可能发生。

标准对c_str返回的指针的值没有限制(除了它指向一个以null结尾的c-string),所以您的代码本质上是不可移植的。

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

相关文章: