Search code examples
c++pointersstldangling-pointer

Is destructor called when removing element from STL container?


Say I have two containers storing pointers to the same objects:

std::list<Foo*> fooList;
std::vector<Foo*> fooVec;

Let's say I remove an object from one of these containers via one if its methods:

std::vector<Foo*>::iterator itr = 
  std::find( fooVec.begin(), fooVec.end(), pToObj );
fooVec.erase( itr );

CppReference says that this calls the object's destructor. Does this mean that the pointer to the object in fooList is a dangling pointer?

I'd prefer not to use reference counted pointers. How can this problem be handled?


Solution

  • No.

    When you remove a pointer from a container, all you've done is take that pointer value from the container, nothing is deleted. (i.e.: pointers have no destructor.)

    However, it's dangerous to have pointers of things in containers. Consider:

    std::vector<int*> v;
    v.push_back(new int());
    v.push_back(new int());
    v.push_back(new int());
    

    If you never go through the container and delete each one, you've leaked. Worse is it's not exception safe. You should use a pointer container, which will delete things it points to when they are erased. (And all get erased when the container destructs.)

    In your case, though, since you are sharing a pointer in different places, I can't see an argument against shared_ptr; that's exactly what it was made for.