Legality of COW std::string implementation in C++11

acm picture acm · Aug 30, 2012 · Viewed 27.8k times · Source

It had been my understanding that copy-on-write is not a viable way to implement a conforming std::string in C++11, but when it came up in discussion recently I found myself unable to directly support that statement.

Am I correct that C++11 does not admit COW based implementations of std::string?

If so, is this restriction explicitly stated somewhere in the new standard (where)?

Or is this restriction implied, in the sense that it is the combined effect of the new requirements on std::string that precludes a COW based implementation of std::string. In this case, I'd be interested in a chapter and verse style derivation of 'C++11 effectively prohibits COW based std::string implementations'.

Answer

Dave S picture Dave S · Aug 30, 2012

It's not allowed, because as per the standard 21.4.1 p6, invalidation of iterators/references is only allowed for

— as an argument to any standard library function taking a reference to non-const basic_string as an argument.

— Calling non-const member functions, except operator[], at, front, back, begin, rbegin, end, and rend.

For a COW string, calling non-const operator[] would require making a copy (and invalidating references), which is disallowed by the paragraph above. Hence, it's no longer legal to have a COW string in C++11.