Does std::pair destroy its dynamically allocated objects?

No.

std::vector does not destroy objects whose pointers were added to it by push_back(new T).

Neither does std::pair.


Both vector and pair destroy their elements.

Neither vector nor pair destroy or deallocate objects pointed by their elements.

Some examples:

{
    std::vector<int> v {42};
}

Vector allocated dynamically, and deallocated.

{
    std::vector<int*> v {new int};
}

Vector allocated dynamically, and deallocated. I allocated dynamically, and leaked the allocation.

{
    std::pair<int, int> v {42, 24};
}

No dynamic allocation whatsoever. Great.

{
    std::pair<int*, int*> v {new int, new int};
}

I allocated dynamically twice, and leaked both.

{
    std::pair<int*, int*> v {new int, new int};
    delete v.first;
    delete v.second;
}

No leak.... but don't do this. Avoid unnecessary dynamic allocation, and don't use owning bare pointers.

Tags:

C++

Stl