Advertisement
Intermediate C++, Strings & string_view

How does std::string manage memory and what is SSO?

Short answer

std::string allocates a heap buffer for its characters and grows it as needed (amortized, like vector).

Save C++ mock interview
Advertisement
AModel answer
std::string allocates a heap buffer for its characters and grows it as needed (amortized, like vector). Most implementations use Small String Optimization (SSO): short strings are stored inline in the object itself, avoiding heap allocation entirely, which speeds up common short-string usage. Larger strings spill to the heap.
std::string s = "hi";      // likely stored inline (SSO), no heap alloc
Real-world example
Short identifiers benefit from SSO, avoiding heap allocations in hot string-heavy code.
Likely follow-ups
  • What is Small String Optimization? | When does a string use the heap?
Related topics