Where is a std::string allocated in memory?

后端 未结 6 1637
我在风中等你
我在风中等你 2021-02-01 15:02

Here is a function:

void foo() {
   string str = \"StackOverflo\";
   str.push_back(\'w\');
}

When we declare the string inside the function, i

6条回答
  •  滥情空心
    2021-02-01 15:34

    On Windows platform, in C++, with std::string, string size less than around 14 char or so (known as small string) is stored in stack with almost no overhead, whereas string size above is stored in heap with overhead. Usually platform and compiler dependent which can be tweaked with optimization options.

    std::string myStr {"Hello World"}; // stored in program stack std::string myStr {"StackOverflow saved life of a programmer" }; //pointer is stored in program stack whereas memory for string and is allocated in heap

    Below link has good explanation. https://blogs.msmvps.com/gdicanio/2016/11/17/the-small-string-optimization/

提交回复
热议问题