Copy-on-write support in STL

自古美人都是妖i 提交于 2019-11-30 16:55:22

问题


I was just reading a Wikipedia article on Copy-on-write (curious if there are any filesystems that support it), and was surprised by the following passage:

COW is also used outside the kernel, in library, application and system code. The string class provided by the C++ standard library, for example, was specifically designed to allow copy-on-write implementations:

std::string x("Hello");

std::string y = x;  // x and y use the same buffer

y += ", World!";    // now y uses a different buffer
                    // x still uses the same old buffer

I didn't know that copy-on-write was every supported in STL. Is that true? Does it apply to other STL classes, e.g. std::vector or std::array? Which compilers support that optimization (in particular, I wonder about G++, Intel C++ compiler and Microsoft C++ compiler)?


回答1:


The string class provided by the C++ standard library, for example, was specifically designed to allow copy-on-write implementations

That is half-truth. Yes, it started design with COW in mind. But in the rush the public interface of std::string was messed up. Resulting it getting COW-hostile. The problems were discovered after the standard published, and we're stuck with that ever since. As stands currently std::string can not be thread-safely COW-ed and implementations in the wild don't do it.

If you want a COW-using string, get it from another library, like CString in MFC/ATL.




回答2:


gcc uses copy-by-reference for std::string. As of version 4.8, it is still doing that for C++11, despite it violating the standard.

See here:

  • Is std::string refcounted in GCC 4.x / C++11?
  • Turning off COW in GCC


来源:https://stackoverflow.com/questions/17298164/copy-on-write-support-in-stl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!