Assume I have defined a class like this:
class foo {
private:
std::vector< int* > v;
public:
...
void bar1()
{
for (int i = 0; i < 10; i++) {
int *a = new int;
v.push_back( a );
}
};
void bar2()
{
std::vector< int >::iterator it = v.begin();
for ( ; it != v.end(); it++ )
std::cout << (*it);
v.clear();
}
};
In short, I push back some pointers in a vector, later I clear the vector. The question is, does this code has memory leak? I mean by clearing the vector, are the pointers deleted properly?
I think the shortest and clearest solution would be:
Yes, the code has a memory leak unless you delete the pointers. If the
foo
class owns the pointers, it is its responsibility to delete them. You should do this before clearing the vector, otherwise you lose the handle to the memory you need to de-allocate.You could avoid the memory management issue altogether by using a
std::vector
of a suitable smart pointer.You can use
for_each
:Nope you only clear the vector storage. Allocated memory with 'new' is still there.