Where does a std::vector allocate its memory?

后端 未结 4 1978
生来不讨喜
生来不讨喜 2020-12-13 13:53

Consider the following code snippet:

#include 
using namespace std;

void sub(vector& vec) {
    vec.push_back(5);
}

int main()         


        
4条回答
  •  旧时难觅i
    2020-12-13 14:39

    All containers in the STL are parameterized with template arguments, usually the last argument is called A or Allocator and defaults to std::allocator<...> where ... represents the type of the value stored within the container.

    The Allocator is a class that is used to provide memory and build/destroy the elements in this memory area. It can allocate memory from a pool or directly from the heap, whichever you build the allocator from. By default the std::allocator is a simple wrapper around ::operator new and will thus allocate memory on the heap as you inferred.

    The memory is allocated on demand, and is deallocated at the very least when the vector's destructor is called. C++11 introduces shrink_to_fit to release memory sooner too. Finally, when the vector outgrow its current capacity, a new (larger) allocation is made, the objects are moved to it, and the old allocation is released.

    As will all local variables, the destructor is called when executed reaches the end of the scope it has been declared into. So, before the function is exited, the vector destructor is called, and only afterward does the stack shrinks and control returns to the caller.

提交回复
热议问题