I was reading something like 'std::string doesn't use free store (heap storage) for short strings'. It made me question if it's been implemented in any of STL implementations? It would be nice to do some simple operations with short strings and never worry about bad_alloc as in case when stack memory is used. Maybe this isn't quite possible... Opinions?
I'm not completely sure how you would do this. In order to use the stack, it would have to be a local variable, and thus it (the char array we are pointing at) would be destroyed after the function runs, meaning you can't actually use it.
Where did you see this? Or did you just remember it?
"The C++ Programming Language" 3rd ed. p 582 (20.3):
Many common uses of strings are better served by implementations that minimize copying, use no free store for short strings, allow for simple modification of longer strings, etc.
I can imagine using stack arrays of fixed length, which is supplied as a template parameter, but that's certainly not what std::string is about... So I don't understand that sentence I quoted.
Ahh. What they mean is that std::string does NOT have those attributes, and for those situations you would be better served using a different data type that is more specialized for those requirements.
The implementers are free to make it as they wish.
E.g. this way:
1 2 3 4 5 6 7 8
class string {
private:
char shortStringStorage[8];
char* longStringStorage;
...
}
The methods of the string class would store strings up to 8 bytes in the shortStriongStorage array and others in longStringStorage allocated from the heap.