In C++, std::string is essentially a dynamic char vector wrapper. But because strings are used everywhere, copying them constantly or triggering dynamic heap allocations can degrade application speeds. Modern C++ uses memory layouts and view classes to eliminate string copy latency.
Let's look at how strings are packed, small string optimization, and string views.
Small String Optimization (SSO)
To avoid slow heap allocation system calls for tiny words, modern compiler implementations of std::string use Small String Optimization (SSO).
A string object contains a pointer to the heap, a size variable, and a capacity variable (usually summing to 24 or 32 bytes). Under SSO, the string object repurposes that exact stack space as a small, internal character buffer. If your string fits within this size (typically under 15 characters on 64-bit systems), the characters are stored directly on the stack inside the string object itself. Zero heap allocations are made!
* The Key Metaphor: SSO is like keeping your keys in your pocket (stack storage). If you only have a few keys, you keep them on your person. If you suddenly buy a massive set of tools and equipment, you cannot fit them in your pocket, so you rent a public storage locker (heap allocation) and keep the locker ticket receipt in your pocket.
String Views: Zero Copy Slices
When you pass a string to a function, you must pass it by const reference to avoid a copy. But what if you want to pass a string literal "Hello" or a slice of an array? Passing them requires instantiating a temporary string, which triggers a heap allocation.
C++17 solved this by introducing std::string_view (in the <string_view> header). A string view is a non owning wrapper. It holds only two variables: a pointer to the start of the characters, and a size integer. It never allocates heap memory.
The String View Lifetime Trap
Because std::string_view does not own the memory it references, it is highly vulnerable to dangling pointers. If the underlying string object is modified or goes out of scope, the view is left pointing to dead memory: