If I have the following code,
Foo *f = new Foo(); vector<Foo*> vect; vect.push_back(f); // do stuff vect.erase(f);
Did I create a memory leak? I guess so, but the word erase gives the feeling that it is deleting it.
Writing this, I am wondering if it is not a mistake to put a pointer in a STL vector. What do you think?
Yes, you created a memory leak by that. std::vector and other containers will just remove the pointer, they won’t free the memory the pointer points to.
It’s not unusual to put a pointer into a standard library container. The problem, however, is that you have to keep track of deleting it when removing it from the container. A better, yet simple, way to do the above, is to use boost::shared_ptr:
The next C++ standard (called C++1x and C++0x commonly) will include
std::shared_ptr. There, you will also be able to usestd::unique_ptr<T>which is faster, as it doesn’t allow copying. Usingstd::unique_ptrwith containers in c++0x is similar to theptr_containerlibrary in boost.