受CString的影响,我一直以为std::string也是Copy On Write机制的。可实际测试下来却不太一样:

cpp
 1#include <string>
 2#include <cstdio>
 3
 4int main()
 5{
 6    std::string a = "test";
 7    std::string b = a;
 8    printf("Before modify:\n");
 9    printf("a = 0x%p\n", a.c_str());
10    printf("b = 0x%p\n", b.c_str());
11
12    b[2] = 'x';
13    printf("After modify:\n");
14    printf("a = 0x%p\n", a.c_str());
15    printf("b = 0x%p\n", b.c_str());
16
17    return 0;
18}

用VC++2008编译后运行,输出结果:

text
1Before modify:
2a = 0x0012FE94
3b = 0x0012FE6C
4After modify:
5a = 0x0012FE94
6b = 0x0012FE6C

用mingw-g++-4.4.0编译后运行,输出结果:

text
1Before modify:
2a = 0x003E3E6C
3b = 0x003E3E6C
4After modify:
5a = 0x003E3E6C
6b = 0x003E2BBC

可以发现,在不同的STL实现中,并不一定都使用Copy On Write的机制。看来,如果需要注重效率的话,还是应该尽量考虑使用const std::string&的方式来传递参数。