关于string的Copy-On-Write
ckt 2007-09-08 12:08:19 看了篇关于string使用Copy-On-Write的文章:
http://blog.csdn.net/ckt1120/archive/2007/09/08/1777004.aspx
#include <string>
#include <iostream>
using namespace std;
void main()
{
string str1("hello world!");
string str2 = str1;
printf ("Before Copy-On-Write:\n");
printf ("str1's address: %x\n", str1.c_str());
printf ("str2's address: %x\n", str2.c_str());
str1[1] = 'q';
str2[2] = 'g';
string str3 = str2;
printf ("\nAfter Copy-On-Write:\n");
printf ("str1's address: %x\n", str1.c_str());
printf ("str2's address: %x\n", str2.c_str());
printf ("str3's address: %x\n", str3.c_str());
}
有个疑惑想请教:对于str3,我觉得应该是和str2共用一段内存空间,即打印出的地址应该相同。
但是结果却不同?