I declare a variable string s;
and do s = "abc"; now it has buffer of 3 characters.
After
s = "abcd" it has a buffer of 4 characters.
Now after the third statement
s = "ab" question is will it keep the buffer of 4 characters or will it reallocate a 2 character buffer?
If it will allocate 2 character buffer is there any way I can tell it to keep the allocated maximum buffer.
So does it keep the buffer of maximum size ever allocated ?
s = "ab"
s="abc"
s="a"
s="abcd"
s="b"
Now it should keep a buffer of size 4.
Is that possible?
It will not reallocate the buffer. I don’t know if it’s mentioned in the standard, but all the implementations I have ever seen issue a reallocation only if they need to increase the capacity. Never to decrease. Even if you have a string with 4 characters and call
.resize(2)or.reserve(2)the capacity will not change. In order to force the string (or containers) to reallocate memory to fit the exact size, there’s a simpleswaptrick for thatWhat happens here? You create a temporary from s which will have its capacity exactly equal to
s.size()then swap it with your original string. The destructor of the temporary will free all the necessary resources.Again, I am not claiming this is standard, but all the implementations I’ve seen have this behavior.