copy-on-write形成的一个问题

copy-on-write是一种颇有效率的作法,可是也会致使一些问题。ios

std::string 的 c_str() 会返回字符串对象对应的指针,而 std::string 大多数采用了 copy-on-write 的方法,所以在使用 c_str() 方法时,要格外注意。spa

示例代码(一看就懂):指针

 1 #include<string>
 2 #include<iostream>
 3 
 4 int
 5 main(void){
 6     std::string s("hello");
 7     std::string sub = s;
 8 
 9     std::cout << s << std::endl;
10     std::cout << sub << std::endl;
11 
12     char* s_ptr = (char*)s.c_str();
13     char* sub_ptr = (char*)sub.c_str();
14 
15     if(s_ptr == sub_ptr)
16         std::cout << "the two pointers are same" << std::endl;
17 
18     s_ptr[1] = 'o';
19 
20     std::cout << s << std::endl;
21     std::cout << sub << std::endl;
22 
23     return 1;
24 }

最终输出是code

hello对象

helloblog

the two pointers are same字符串

hollostring

holloit

相关文章
相关标签/搜索