Copy-on-write support in STL

2019-02-12 16:41发布

问题:

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