Do I need to delete something that has been new'd inside a vector?

Case in point:

1
2
3
4
vector<int*> myvec;
myvec.push_back(new int);

myvec.clear() // this will remove the dynamically allocated integer 


Does this work? I know the golden rule is to use delete whenever I use new, but in the vector documentation it says this for the vector::clear() function:

All the elements of the vector are dropped: their destructors are called, and then they are removed from the vector container, leaving the container with a size of 0.


Can someone please confirm or deny that this function would effectively call "delete" for every pointer in my vector?
No, this will not call delete.

The elements of your vector are pointers-to-int, which are non-class types. Calling a destructor on an object of non-class type compiles, but does nothing at all (it's known as "pseudo destructor call")

Best practice when holding pointers in a container is to use smart pointers (vector<unique_ptr<int>> or vector<shared_ptr<int>>, depending on your goals) or specialized pointer container (boost::ptr_vector<int>). In those cases you would never have to call delete.
Last edited on
ok, thanks :)
Topic archived. No new replies allowed.