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?
The pointer itself will get destroyed, but it's up to the programmer to explicitly free the memory to which it refers (assuming the memory isn't used elsewhere).
delete keyword in C++Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed. The delete operator has void return type does not return a value.
std::vector does call the destructor of every element it contains when clear() is called. In your particular case, it destroys the pointer but the objects remain.
No, memory are not freed. In C++11, you can use the shrink_to_fit method for force the vector to free memory.
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:
{
boost::shared_ptr<foo> f(new foo);
std::vector< boost::shared_ptr<foo> > v;
v.push_back(f);
v.erase(v.begin());
} /* if the last copy of foo goes out of scope, the memory is automatically freed */
The next C++ standard (called C++1x and C++0x commonly) will include std::shared_ptr
. There, you will also be able to use std::unique_ptr<T>
which is faster, as it doesn't allow copying. Using std::unique_ptr
with containers in c++0x is similar to the ptr_container
library in boost.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With