Hello,
I have in my class Ordinateur a vector of *Composant :
class Ordinateur {
string type;
vector<Composant*> Composants;
...
}
How do i write my destructor ? I read a lot of contradictory answers here on StackOverflow so i'm a bit lost.
1st version :
virtual ~Ordinateur()
{
for (int i = 0; i < Composants.size(); i++)
{
delete Composants[i];
}
Composants.clear();
}
2nd Version
virtual ~Ordinateur()
{
Composants.clear();
}
What about :
virtual ~Ordinateur()
{
for (int i = 0; i < Composants.size(); i++)
{
delete Composants[i];
}
}
I would like to avoid memory leaks ...
Use the first version if you allocated the Composant
elements using new Composant();
otherwise the second version will leak memory.
virtual ~Ordinateur()
{
for (int i = 0; i < Composants.size(); i++)
{
delete Composants[i]; // this is needed to free the memory
}
// Composants.clear(); // not needed vector cleans itself up
}
However you may consider doing this instead:
class Ordinateur {
std::string type;
std::vector<std::unique_ptr<Composant>> Composants;
...
}
Then you don't need to write a destructor at all, the elements will delete themselves. And there is no need to call Composants.clear();
in the destructor because the vector will do that itself when your object is destroyed.
If the vector owns them and they point to new
'ed objects, then your first variant is correct.
The call to vector::clear() is not necessary. It will be done by the destructor anyway. It does nothing bad apart from wasting CPU cycles though.
You should still use smart pointers, so you don't have such problems.
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