Suppose I have a string and I take a reference to a character:
std::string a = f(); // shared
char& c = a.front();
Should the string be copied or not? One might argue, no taking a reference is different from "writing" so no copying, but one might also argue that reference can be used to change the string later, and the string doesn't know when this would happen so it has to pessimistically make a copy.You get bugs if you go with the former, and bad performance if you go with the latter.
const char& c = a.front();
Unfortunately the STL has an overload for the non-const version, which would cause this problem. It's hard to imagine the cases where you'd need a mutable reference to a single character. It can fit into the same register that the reference would live, so even as an immutable reference it doesn't make much sense. s[3] = 'h';
involves forming a mutable reference and then assigning its pointee.The way I think about it, to make CoW strings really usable in C++, you basically have to make strings immutable, like many newer languages like Python. That ship has sailed by the time standardization for C++ happened.
Result: many programs forgot
Convention: every non-NULL pointer returned by malloc() should be passed to free() at most once
Result: programs free()'d these pointers twice
Convention: programs should only write to memory addresses [p, p+s) if p is a non-NULL pointer returned by malloc(s), and before calling free(p)
Result: many programs wrote beyond p+s, or wrote to the memory after calling free()
Remind me again, what's a convention?
The benefit of a shared string is you might save some space. That’s fine but I think most programmers today will choose am explicitly shared type when they need it, and a fast string for most cases.