Here is a function:
void foo() {
string str = \"StackOverflo\";
str.push_back(\'w\');
}
When we declare the string inside the function, i
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.