[英]std::string copy constructor NOT deep in GCC 4.1.2?
我想知道我是否誤解了一些東西:來自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!");
它將內容復制到新字符串中。
你的string
實現完全有可能使用copy-on-write來解釋行為。 雖然對於較新的實現(並且不符合C ++ 11實現),這種可能性較小。
該標准對c_str
返回的指針的值沒有限制(除了它指向以null結尾的c字符串),因此您的代碼本質上是不可移植的。
編譯器中的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.