我想知道我是否误解了什么:复制构造函数来自std::string
not复制其内容?
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!");
它将内容复制到新字符串中。
完全有可能你的string
实现使用写入时复制这可以解释该行为。尽管对于较新的实现(并且不符合 C++11 实现),这种情况不太可能发生。
标准对返回的指针的值没有限制c_str
(此外它指向一个以 null 结尾的 c 字符串),因此您的代码本质上是不可移植的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)