Search code examples
c++vectorallocation

Delete pointer allocation after adding it to vector


Once you add an object to a vector in C++, and delete the pointer to that object, will the object inside the vector get deleted too?

for example,

int i = 0;
std::vector<A> aVect;
while(i++ < 10)
{    
    A *ptrToA = new A();
    aVect.push_back(*ptrToA);
    delete ptrToA;
}

would it still be valid to call:

aVect.at(2);

Will the call to "delete" destroy the object that was added to the vector, or will it only deallocate the object of the pointer?


Solution

  • Yes you can delete the pointer because, as others have noted you dereference the pointer to it is copied into the vector by value.

    It would be more efficient to just construct into the vector like this and avoid new/delete entirely:

    int i = 0;
    while(i++ < 10)
    {    
        std::vector<A> aVect;
        aVect.push_back(A());
    }
    

    In C++11 a copy will not be made - the rvalue version of push_back will be used - A will be constructed into it's slot in the vector.

    You may not want to create a new vector each time???

    std::vector<A> aVect;
    int i = 0;
    while(i++ < 10)
    {    
        aVect.push_back(A());
    }