Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy-on-write support in STL

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)?

like image 862
Septagram Avatar asked Jun 25 '13 13:06

Septagram


2 Answers

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.

like image 144
Balog Pal Avatar answered Sep 30 '22 11:09

Balog Pal


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
like image 23
Brent Bradburn Avatar answered Sep 30 '22 11:09

Brent Bradburn