In C++, std::string::reserve() asks the string to make sure its buffer can hold at least n characters without another allocation.
It does not add characters and does not change size(). Include <string>.
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
Pass the capacity you want to prepare for.
C++
s.reserve(256);
s += "lots of text...";
Call
What it does
s.reserve(n)
Ensure capacity is at least n. May allocate now.
s.reserve()
C++20: non-binding shrink request similar in spirit to shrink_to_fit (implementation-defined). Prefer shrink_to_fit() for intent.
If n is less than or equal to the current capacity, most libraries do nothing. reserve never reduces size().
Library declarations
C++
void reserve(size_type new_cap = 0);
Parameters
Parameter
Description
new_cap
Desired minimum capacity. Optional; meaning of the zero-argument form is a non-binding shrink request since C++20.
Return Value
Return Value
Description
void
No return value. Check capacity() afterward if you need confirmation.
C++ Examples
Example 1 — Basic reserve()
Reserve space, then append without surprise growth from tiny starts.