Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destruction order of class data members?

Imagine a class like this:

class foo {
public:
    foo() : _bar{new bar}, _baz{new baz} {}
private:
    unique_ptr<bar> _bar;
    unique_ptr<baz> _baz;
};

So whenever an instance of foo gets destructed, then in what order will the data members of it be destroyed, if that's defined behavior at all?

Let's say that _baz does depend on the existance of _bar, maybe it uses some resource that _bar owns (let's assume it knows about the _bar object, even though the constructor doesn't reflect this). So in this case, if _bar gets destructed first (when its time to destruct foo), then _baz could potentially try to access some resource which has been freed by _bar's destructor.

An obvious solution is to implement a destructor in foo, which manually frees _baz and _bar in the right order, but what if there's no destructor implemented? Is there a default behavior that defines the destruction order of data members?

like image 478
notadam Avatar asked Mar 20 '15 13:03

notadam


1 Answers

The order of destruction of data members is the reverse of their order of declaration, the same way as variables declared within a scope:

{
  // a, b constructed in that order
  bar a;
  baz b;

} // b, a destroyed in that order
like image 191
juanchopanza Avatar answered Oct 12 '22 10:10

juanchopanza