Where is a std::string allocated in memory?

后端 未结 6 1636
我在风中等你
我在风中等你 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:27

    "StackOverflo", the string literal, is likely stored in the read-only data space of the binary and is mapped into memory when the program starts. You can read more about this here.

    str, the class instance`, is allocated on the stack. But the memory its constructor allocates to make a copy of the string literal is allocated on the heap.

    The foo function returns a copy of str, so what you have coded is ok.

提交回复
热议问题