Copy-on-write support in STL
Asked Answered
S

2

12

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

Stonybroke answered 25/6, 2013 at 13:6 Comment(5)
Actually, std::string cannot be copy-on-write anymore, see here.Incunabulum
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.Rigveda
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.Rebroadcast
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?Stonybroke
@Stonybroke it generally performs worse in multithreaded code due to the additional locking requiredAnsley
N
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.

Nomism answered 25/6, 2013 at 13:42 Comment(0)
C
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:

Cataphoresis answered 15/8, 2015 at 18:34 Comment(1)
How about these days?Cattail

© 2022 - 2024 — McMap. All rights reserved.