Ideally, an immutable string class would only need one memory allocation for each string. Even the reference count could be stored in the same chunk of memory that holds the string itself.
A trivial implementation of string
and shared_ptr
would allocate three distinct pieces of memory for shared_ptr<string const>
:
- Memory for the string buffer
- Memory for the string object
- Memory for the reference count
Now, I know that when using std::make_shared()
, it is possible for a smart implementation to combine the last two into a single allocation. But that would still leave two allocations.
When you know that the string is immutable, the string buffer won't be reallocated, hence it should be possible to integrate it with the string object, leaving only one allocation.
I know that some string implementations already use such optimizations for short strings, but I'm after an implementation that does this regardless of string length.
My questions are: Is my reasoning sound? Is an implementation actually permitted and able to do this? Can I reasonably expect from a good quality standard library to implement this optimization? Do you know of contemporary library implementations which do this?
Or is this something I would have to implement myself?