Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does myVector.erase(myPtr) delete the object pointed by myPtr?

Tags:

c++

stl

vector

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?

like image 262
Barth Avatar asked Nov 11 '08 16:11

Barth


People also ask

Does erase delete a pointer?

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).

Does deleting a pointer delete the object C++?

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.

Does vector clear delete objects?

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.

Does vector clear deallocate memory?

No, memory are not freed. In C++11, you can use the shrink_to_fit method for force the vector to free memory.


1 Answers

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.

like image 60
Johannes Schaub - litb Avatar answered Oct 19 '22 02:10

Johannes Schaub - litb