In C++, std::string::shrink_to_fit() asks the string to reduce unused capacity so the buffer is closer to size().
The request is non-binding: the library may keep a larger capacity. Include <string>. (C++11)
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax
Call after you no longer need a large spare buffer.
C++
s.shrink_to_fit();
Call
What it does
s.shrink_to_fit()
Non-binding request to shrink capacity toward size.
After a large temporary growth, clear() sets size to 0 but often keeps capacity. shrink_to_fit() is the usual follow-up when you want to hint that spare room can go away.
Library declarations
C++
void shrink_to_fit();
Parameters
Parameter
Description
None
shrink_to_fit() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
void
No return value. Inspect capacity() to see what happened.