写时拷贝的意思是:在例子中string str1 = "linux_ever"; string str2 = str1;可以看到str1和str2中的指针变量指向相同的内存地址。当改变str的内容的时候才拷贝该对象。
string str1 = "linux_ever";执行完之后,str1对象的内容就是"linux_ever",会调用复制构造函数。
string str2 = str1;//执行完之后,会调用str2的复制构造函数,str2中的指针成员变量指向刚才str1中指向成员变量指向的内存单元。
当修改了str1的时候,就将str1的内存单元重新分配,将之前指向的内存单元中的内存拷贝过来,并修改相应的值。理所应当地,刚才的内存空间被str2单独占用了。所以接下来即使修改了str2的值,它的地址也没有发生改变。
在第二个程序中,先修改了str2,所以就将str2的内存单元重新分配,将之前指向的内存单元中的内存拷贝过来,并修改相应的值。理所应当地,刚才的内存空间被str1单独占用了。所以接下来即使修改了str1的值,它的地址也没有发生改变。
/************************************************************************* > File Name: string_copy_on_write.cpp > Author: > Mail: > Created Time: 2016年03月25日 星期五 20时22分39秒 ************************************************************************/ #include <iostream> #include <string> #include <stdio.h> using namespace std; int main() { string str1 = "linux_ever"; string str2 = str1; cout << "查看str1和str2中内容指向的地址: " << endl; printf("str1's address is %x\n", str1.c_str()); printf("str2's address is %x\n", str2.c_str()); cout << "\n输出两个string对象的值之后的内存地址:" << endl; cout << "str1 = " << str1 << endl; cout << "str2 = " << str2 << endl; printf("str1's address is %x\n", str1.c_str()); printf("str2's address is %x\n", str2.c_str()); cout << "\n修改了str1之后的地址:" << endl; str1[0] = 'u'; printf("str1's address is %x\n", str1.c_str()); printf("str2's address is %x\n", str2.c_str()); cout << "\n修改了str2之后的地址:" << endl; str2[0] = 'w'; printf("str1's address is %x\n", str1.c_str()); printf("str2's address is %x\n", str2.c_str()); return 0; }
/************************************************************************* > File Name: string_copy_on_write.cpp > Author: > Mail: > Created Time: 2016年03月25日 星期五 20时22分39秒 ************************************************************************/ #include <iostream> #include <string> #include <stdio.h> using namespace std; int main() { string str1 = "linux_ever"; string str2 = str1; cout << "查看str1和str2中内容指向的地址: " << endl; printf("str1's address is %x\n", str1.c_str()); printf("str2's address is %x\n", str2.c_str()); cout << "\n输出两个string对象的值之后的内存地址:" << endl; cout << "str1 = " << str1 << endl; cout << "str2 = " << str2 << endl; printf("str1's address is %x\n", str1.c_str()); printf("str2's address is %x\n", str2.c_str()); cout << "\n修改了str2之后的地址:" << endl; str2[1] = 'u'; printf("str1's address is %x\n", str1.c_str()); printf("str2's address is %x\n", str2.c_str()); cout << "\n修改了str1之后的地址:" << endl; str1[1] = 'w'; printf("str1's address is %x\n", str1.c_str()); printf("str2's address is %x\n", str2.c_str()); return 0; }输出结果: