Where is a std::string allocated in memory?

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

    The object str (it is the instance of the class std::string) is allocated in the stack. However, the string data itself MAY BE allocated in the heap. It means the object has an internal pointer to a buffer that contains the actual string. However, again, if the string is small (like in this example) usually the string class will have what we call "small string optimization". It means that the size of the std::string object itself is enough to contain the data of the string if it's small enough (usually around 23 bytes + 1 byte for null-terminator)... then if the content is bigger than this, the string data will be allocated in the heap.

    Usually you can return your string normally. C++ can handle this for you. The move semantics can take care of whatever necessary here to return the string object pointing to the same string data of the original string, avoiding doing unecessary copies.

提交回复
热议问题