Search code examples
c++dynamic-memory-allocationstdvectorstatic-memory-allocation

What is the difference between static and dynamic allocation of vector in c++?


I know the difference for following cases:

case 1: int a[10];

for case 1, memory for array is allocated on stack.

case 2: int *a = new int[10];

for case 2, memory is allocated on heap and a pointer is returned.

But what is the difference between below two declarations, as for vector memory is always allocated on heap

vector<int> v1;
vector<int> *v2 = new vector<int>();

Solution

  • The following two statements create a vector<> however there are several differences between the two.

    vector<int> v1;
    vector<int> *v2 = new vector<int>();
    

    First of all the actual vector data storage is going to be allocated from the heap or whatever source the designated memory allocator uses (see Where does a std::vector allocate its memory?) and this is the same for both.

    The two differences are (1) where the vector<> management data is stored and {2} the lifetime for the vector<> and its allocated memory.

    In the first case the vector<> management data is stored on local memory, the stack, and when the vector<> variable goes out of scope, the destructor is called to eliminate the vector data storage space on the heap and the vector management space on the stack. In the first case when the vector<> variable goes out of scope, the vector<> memory is properly released.

    In the second case both the vector<> storage data space and the vector<> management space is on the heap.

    So when the pointer variable containing the address of the vector<> goes out of scope, the destructor for the vector<> itself is not called. The result is memory that is not recovered since the destructor that would clean up and release the allocated memory for both the data storage area of the vector<> and the management storage area is never called.

    One possibility for the second case to ensure that the vector<> is cleaned up properly is to use a smart pointer which when it goes out of scope will also trigger the destructor for the thing pointed to.

    In most cases the need for the second case, using new to create the vector<> is rare and the first case is not only the most common but also safer.