3 ms·
> The solution is to invoke the copy on the access of `t[1]`, which is what libstdc++ does. No, libstdc++ specifically DOES NOT unshare the string buffer when
by sltkr 14y ago
> The solution is to invoke the copy on the access of `t[1]`, which is what libstdc++ does.
No, libstdc++ specifically DOES NOT unshare the string buffer when calling the CONST version of operator[] (really, go look it up). That's the whole point of CoW: to only copy when the string is written (or at least, when you have to pessimistically assume it will be, because somebody has gotten a non-const reference to its contents).
You could "fix" the issue by unsharing the buffer whenever a const iterator/reference to the string is returned, but then you lose most of the performance benefit of sharing the buffer in the first place, because most strings that are constructed are read at some point.
Because of these difficulties we'll see standard library implementations move away from copy-on-write implementations and then the whole issues doesn't exist. That is to say: the performance of the test case the blog author describes will be consistently “bad” because std::string will behave pretty much like a std::deque/std::vector.