The Bad
This is an old question, but even as of C++1z/C++2a in Visual Studio 2019
, stringstream
has no ideal way of reserving a buffer.
The other answers to this question do not work at all and for the following reasons:
calling reserve on an empty string yields an empty string, so stringstream
constructor doesn't need to allocate to copy the contents of that string.
seekp
on a stringstream
still seems to be undefined behavior and/or does nothing.
The Good
This code segment works as expected, with ss
being preallocated with the requested size.
std::string dummy(reserve, '\0');
std::stringstream ss(dummy);
dummy.clear();
dummy.shrink_to_fit();
The code can also be written as a one-liner std::stringstream ss(std::string(reserve, '\0'));
.
The Ugly
What really happens in this code segment is the following:
dummy
is preallocated with the reserve, and the buffer is subsequently filled with null bytes (required for the constructor).
stringstream
is constructed with dummy. This copies the entire string's contents into an internal buffer, which is preallocated.
dummy
is then cleared and then erased, freeing up its allocation.
This means that in order to preallocate a stringstream
, two allocations, one fill, and one copy takes place. The worst part is that during the expression, twice as much memory is needed for the desired allocation. Yikes!
For most use cases, this might not matter at all and it's OK to take the extra fill and copy hit to have fewer reallocations.