Andrei Margeloiu Andrei Margeloiu - 4 years ago 141
C++ Question

Where is a std::string allocated in memory?

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download