Copy-on-write(COW) 是计算机程序设计中的一种优化策略。The fundamental idea is that if multiple callers ask for resources which are initially indistinguishable, you can give them pointers to the same resource. This fiction can be maintained until a caller tries to modify its "copy" of the resource, at which point a true private copy is created to prevent the changes becoming visible to everyone else. All of this happens transparently to the callers. The primary advantage is that if a caller never makes any modifications, no private copy need ever be created.
STL中的string的实现就用到了copy on write策略。String is a reference counted, copy on write string class
#include <string>
using namespace std;
main()
...{
string str1 = "hello world";
string str2 = str1;
printf ("Sharing the memory: ");
printf (" str1's address: %x ", str1.c_str() );
printf (" str2's address: %x ", str2.c_str() );
str1[1]='q';
str2[1]='w';
printf ("After Copy-On-Write: ");
printf (" str1's address: %x ", str1.c_str() );
printf (" str2's address: %x ", str2.c_str() );
return 0;
}
本文介绍了计算机程序设计中的优化策略——写时复制(Copy-on-write, COW),并以C++ STL中的string类为例展示了该策略的工作原理。通过具体代码演示了当多个字符串对象共享同一内存区域时,仅在修改时才创建副本的过程。
5628

被折叠的 条评论
为什么被折叠?



