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

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.

Leave a Comment