The memory for string object foo exists in two places in this example. foo itself is on the stack and only occupies some small fixed sized bit of memory (regardless of how many characters are being managed). The characters themselves are on the heap... it is this part of the string object that grows and shrinks as needed and which the string object manages.Code:#include <string> int main() { std::string foo("Hello World"); ... return 0; }
It works kinda similar to this:
The my_string variable called str exists on the stack in a manner similar to how the string object foo does. Also, the str variable has memory allocated to it's ptr member from the heap and data copied into this allocated memory similar to how the string object allocates memory and copies the data it manages. In the case of the string object, this allocated data can grow or shrink as needed as operations (concatenation of several strings for example) are made upon the string object.Code:struct my_string { char * ptr; }; int main() { my_string str; str.ptr = new char[12]; strcpy(str.ptr,"Hello World"); ... return 0; }
So... the string objects themselves are on the stack (unless you create the object itself dynamically) but are fixed and very tiny in the memory they occupy. The data they manage however exists on the heap and can be quite large (millions of characters or larger).