Where is a std::string allocated in memory?

When we declare the String inside the function, is it stored on the Stack or Heap?

The string object itself is stored on the stack but it points to memory that is on the heap.

Why?

The language is defined such that the string object is stored on the stack. string's implementation to construct an object uses memory on the heap.


The object str (it is the instance of the class std::string) is allocated in the stack. However, the string data itself MAY BE allocated in the heap. It means the object has an internal pointer to a buffer that contains the actual string. However, again, if the string is small (like in this example) usually the string class will have what we call "small string optimization". It means that the size of the std::string object itself is enough to contain the data of the string if it's small enough (usually around 23 bytes + 1 byte for null-terminator)... then if the content is bigger than this, the string data will be allocated in the heap.

Usually you can return your string normally. C++ can handle this for you. The move semantics can take care of whatever necessary here to return the string object pointing to the same string data of the original string, avoiding doing unecessary copies.


"StackOverflo", the string literal, is likely stored in the read-only data space of the binary and is mapped into memory when the program starts. You can read more about this here.

str, the class instance`, is allocated on the stack. But the memory its constructor allocates to make a copy of the string literal is allocated on the heap.

The foo function returns a copy of str, so what you have coded is ok.

Tags:

C++

String