In C++, std::string::capacity() tells you how many characters the string\'s current buffer can hold without asking for a bigger block of memory.
Capacity is always >= size(). When you append past capacity, the string allocates a larger buffer (reallocation). 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
Call capacity with empty brackets.
C++
std::size_t cap = s.capacity();
Call
What it does
s.capacity()
Returns the current buffer capacity in characters.
Small-string optimization (SSO) means short strings may live inside the object with a small fixed capacity. Exact numbers differ by library.
Library declarations
C++
size_type capacity() const noexcept;
Parameters
Parameter
Description
None
capacity() takes no parameters. Call it with empty brackets.