string寫時復制:將字符串str1賦值給str2后,除非str1的內容已經被改變,否則str2和str1共享內存。當str1被修改之后,stl才為str2開辟內存空間,並初始化。
#include <cstring> #include <string> #include <cstdio> #include <iostream> using namespace std; void fun1() { string s1 = "hello, world!"; string s2 = s1; cout << "before: " << s2 << endl; char* ptr = const_cast<char*>(s1.c_str()); *ptr = 'f'; cout << "after: " << s2 << endl; } void fun2() { string s1 = "hello, world!"; string s2 = s1; cout << "before: " << s2 << endl; s1[0] = 'f'; cout << "after: " << s2 << endl; } int main() { cout << "fun1: " << endl; fun1(); cout << "fun2: " << endl; fun2(); return 0; }
注意:fun1中,通過char*修改s1行為,並不會觸發stl的復制操作,因為stl並不認為通過char* 對s1的修改是對string s1的修改。