Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor of vector of object

Tags:

c++

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

like image 273
Mxsky Avatar asked Dec 18 '22 23:12

Mxsky


2 Answers

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.

like image 68
Galik Avatar answered Feb 14 '23 14:02

Galik


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.

like image 40
nvoigt Avatar answered Feb 14 '23 16:02

nvoigt