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

限于喜欢 提交于 2019-12-09 14:31:06

问题


I wonder if i misunderstood something: does a copy constructor from std::string not copy its content?

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

This will print "You will get into the IPC hell very soon!!" and it annoys me.

Is this the normal behavior of std::string? I read somewhere that it usually does a deep copy.

However, this works as expected:

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

It copies the contents into the new string.


回答1:


It is entirely possible that your string implementation uses copy-on-write which would explain the behavior. Although this is less likely with newer implementations (and non-conforming on C++11 implementations).

The standard places no restriction on the value of the pointer returned by c_str (besides that it points to a null-terminated c-string), so your code is inherently non-portable.




回答2:


std::string implementation in your compiler must be reference counted. Change one of the strings and then check the pointers again - they would be different.

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.

These are 3 excellent articles on reference counted strings.

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

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

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



来源:https://stackoverflow.com/questions/16604925/stdstring-copy-constructor-not-deep-in-gcc-4-1-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!