Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is a std::string allocated in memory?

Tags:

c++

string

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?

like image 942
Andrei Margeloiu Avatar asked Feb 05 '17 08:02

Andrei Margeloiu


People also ask

Is std::string allocated on heap?

So we can say std::string allocates short strings on the stack, but long ones -- on the heap.

What library is std::string in?

The string class is part of the C++ standard library.

Does C++ string allocate memory?

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.

Is std::string dynamically allocated?

Inside every std::string is a dynamically allocated array of char .


1 Answers

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.

like image 169
R Sahu Avatar answered Oct 08 '22 11:10

R Sahu