std::string 是 copy on write 的??

在网上查点东西,总是看到一篇东西被这里抄、那里抄,都是人云亦云,很少人自己亲自实践。比如copy on write这个概念,在google上搜搜,几乎千篇一律说 STL 的 string 是“写时拷贝”,但实际并不是每家的 STL 都这么实现的。

std::string a("hello, the world");
std::string b = a;
printf("a is 0x%08x, b is 0x%08x\n", a.c_str(), b.c_str());

上面的代码分别在 linux(GCC 4.6.3) 和 windows(VC2010) 中编译一下,结果是不一样的。

实践证明,GCC中是符合Copy-On-Write的:

a is 0x08394014, b is 0x08394014

但是VC2010并没有这样做:

a is 0x0022fa14, b is 0x0022f9ec

所以再提 Copy-On-Write 时一定要注明编译器;而且要考虑到在Windows中使用std::string赋值时的代价。

posted @ 2012-03-20 22:33  Tody.Lu  阅读(231)  评论(0编辑  收藏  举报