List and list elements, where are stored?

前端 未结 7 1609
粉色の甜心
粉色の甜心 2021-01-05 17:59

Given this piece of code:

#include 
(void) someFunction(void) {
    list  l;
    l.push_back(1);
}
  • Where are t
7条回答
  •  悲&欢浪女
    2021-01-05 18:36

    If you changed the function signature to return a list, you could indeed return the list; however the compiler would make a copy of the list, and the copy is the one that would be received by the caller.

    The original list will be destroyed at the end of the function, but the copy will be made before that happens so you will return valid data. If you try to cheat the system and return a pointer or reference instead to avoid the copy, that's when you'll run into undefined behavior.

    The list itself will be on the stack, but the elements contained within will be on the heap. The list will contain pointers that it manages behind the scenes so that you don't have to worry about the storage at all.

提交回复
热议问题