Here is a function:
void foo() { string str = "StackOverflo"; str.push_back('w'); }
When we declare the string inside the function, is it stored on the Stack or Heap? Why?
string foo() { string str = "StackOverflo"; str.push_back('w'); return str; }
Can we return the string reference and continue using somewhere else in the program?
So we can say std::string allocates short strings on the stack, but long ones -- on the heap.
The string class is part of the C++ standard library.
The code calls operator new[] to allocate memory for 10 string object, then call the default string constructor for each array element. In the way, when the delete operator is used on an array, it calls a destructor for each array element and then calls operator delete[] to deallocate the memory.
Inside every std::string is a dynamically allocated array of char .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With