List and list elements, where are stored?

前端 未结 7 1657
粉色の甜心
粉色の甜心 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:44

    Some of it can vary depending on the whim of the compiler and/or library author.

    As it is right now, there's a pretty fair chance the compiler will detect that the result of creating and populating the list is never used, so it would eliminate the entire function as dead code. To prevent that, you might (for example) return the list instead of just letting it be destroyed at the end of the function.

    That only adds new possibilities though. Most compilers implement Return Value Optimization (RVO) and Named Return Value Optimization (NRVO). These basically mean that when/if you return a value (such as your list object) instead of creating an object on the stack and copying it to the destination when you return it, the compiler generates code to generate the object where it's going to be assigned after return. In this case, instead of creating a local function at all, the function will just receive a hidden pointer to the location where it will write the result.

    A std::list normally allocates space for the data to be stored using std::allocate. You can, however, specify a different allocator for it to use. In this case, the space could be allocated almost anywhere.

    Although it's more common with other (sort of) containers like std::string, it's also possible (in at least some cases) to store at least a small amount of data in the object itself, and only allocate space on the heap when/if that overflows. There are some restrictions on this to maintain exception safety and such, but in the case of list it shouldn't be a problem. For example, the first ten ints might be stored in the list object itself, and only when/if you add more than that, it would allocate space on the heap.

提交回复
热议问题