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