A mate of mine told me, I’ve a memory leak in this code
Base
{
public:
vector<Foo*> fooes;
};
Derived : public Base
{
public:
Derived ( )
{
for ( int i = 0 ; i < 10 ; i++ )
{
this.fooes.push_back ( new Foo() );
}
};
};
But he is a very busy man and he can not help me, so I ask you, where is the memory leak? And how do I fix it?
As I understand it, the memory leak is that I do not delete objects, created by new Foo(), so I just can add a destructor to Base, and clear fooes vector, right?
Base
{
public:
vector<Foo*> fooes;
~Base ( )
{
this->fooes.clear();
};
};
The question is:
-
Is this a correct memory leak fix?
-
Will the destructor of
Basebe called before the destructor of Derived, or not? -
Will the
fooesvertor be deleted automatically while deletingBaseor I must delete all members of the class manually?
No, you have to iterate through the elements and manually
deletethem.No (assuming you’re deleting a
Derivedobject).Yes & no. The vector itself will be deleted because it is managed automatically, its members will not:
You should have a
deleteanddelete[]for everynewandnew[]respectively.A better alternative to all this is using smart pointers.