Is it actually guaranteed anywhere that the following reduce-capacity trick will "work"?
int main() {
std::string s = "lololololol";
s = ""; // capacity still non-zero
string(s).swap(s); // ?
}
It doesn't seem to "work" for me (in that the capacity remains non-zero), and I can't find anything in the standard that says anything more than that the "contents" must be swapped between the two [here, identical] objects.
Similarly, for sequence containers:
int main() {
vector<int> v { 1,2,3,4,5 };
v.clear(); // capacity still non-zero
vector<int>(v).swap(v); // ?
}
As far as I'm aware, this "trick" is semi-widely used; perhaps this widespread adoption is misguided?
(Of course, in C++11 we have shrink_to_fit
[albeit non-binding] instead, making this kind of moot.)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…