11

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

Septagram
  • 9,425
  • 13
  • 50
  • 81
  • 2
    Actually, `std::string` cannot be copy-on-write anymore, see [here](http://stackoverflow.com/a/16093748/256138). – rubenvb Jun 25 '13 at 13:10
  • The requirements places on `std::vector` and `std::array` rule out COW for those types. And requirements imposed on `std::string` in C++11 rule out COW for strings too. – juanchopanza Jun 25 '13 at 13:11
  • One example of compiler supporting copy-on-write was Visual C++ 6.0. But not supported anymore since newer versions. As said before, is not supported anymore. – Gonmator Jun 25 '13 at 13:12
  • That's kind of sad :( I enjoyed greatly copy-on-write in Qt classes (it's called 'Implicit sharing' for some reason). What is the motivation for forbidding it? – Septagram Jun 25 '13 at 13:14
  • 3
    @Septagram it generally performs worse in multithreaded code due to the additional locking required – jalf Jun 25 '13 at 13:48

2 Answers2

11

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.

Balog Pal
  • 16,195
  • 2
  • 23
  • 37
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:

Community
  • 1
  • 1
Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173