R
Roland Pibinger
In this example reserve() is indeed unnecessary, but I actually use
std::string to store a rather large binary data with predetermined size,
I think it would be a good idea to give std::string a hint to avoid
unnecessary reallocating.
This is not always the case, unfortunately. Consider:
void foo (const string& str) {
string buf;
buf.reserve (str.size() + 1);
buf.assign (str);
buf.append (1, 'X');
// ...
}
The above code is totally inefficient when string uses a ref-counted
implementation. The reserved space is deallocated immediately by
assign() because of ref-counting; append() possibly triggers a
reallocation again.
If you heavily use string you must either program against your current
std::string implementation and hope that your library vendor does not
change it (Microsoft did) or alternatively use another (your own)
string class. In the latter case it's probably better to split the
string functionality into more than one class (see String and
StringBuilder in Java and C#).
Best wishes,
Roland Pibinger