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

后端 未结 2 1564
日久生厌
日久生厌 2021-02-19 13:08

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

string str1 = \"Hello World\"         


        
2条回答
  •  孤独总比滥情好
    2021-02-19 14:12

    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

提交回复
热议问题