The order of calls to the element constructor and destructor

Oh C ++ guru, I seek your wisdom. Talk to the standard me and tell mine if C ++ guarantees that the following program:

#include <iostream> using namespace std; struct A { A() { cout << "A::A" << endl; } ~A() { cout << "A::~" << endl; } }; struct B { B() { cout << "B::B" << endl; } ~B() { cout << "B::~" << endl; } }; struct C { C() { cout << "C::C" << endl; } ~C() { cout << "C::~" << endl; } }; struct Aggregate { A a; B b; C c; }; int main() { Aggregate a; return 0; } 

will always produce

 A::A B::B C::C C::~ B::~ A::~ 

In other words, are members guaranteed to be initialized in the order of declaration and destroyed in the reverse order?

+85
c ++
Feb 12 '10 at 18:44
source share
4 answers

In other words, are members guaranteed to be initialized in the order of declaration and destroyed in the reverse order?

Yes for both. See 12.6.2

6 Initialization should be performed in the following order:

  • Firstly, and only for the constructor of the most derived class, as described below, the virtual base classes must be initialized in order they appear at the depth from left to right directed acyclic base graph classes, where "from left to right" is the order in which the base class appears in the derived class base specifier list.

  • Then, directly base classes should be initialized in the order of declaration, as they appear in the list-specifier of the base (regardless of the order of mem-initializers).

  • Then, non-static data members must be initialized in the order in which they were declared in the class definition (again, regardless of the order of the MEM initializers).

  • Finally, the compound body constructor instruction is executed. [Please note the declaration submission procedure to ensure that base and member subobjects are destroyed in the reverse order of initialization. -end note]

+106
Feb 12 '10 at 18:50
source share

Yes, they are (non-static members that are). See 12.6.2 / 5 for initialization (construction) and 12.4 / 6 for destruction.

+26
Feb 12 2018-10-12
source share

Yes, standard object warranties are being destroyed in the order in which they were created. The reason is that one object can use another, so it depends on it. Consider:

 struct A { }; struct B { A &a; B(A& a) : a(a) { } }; int main() { A a; B b(a); } 

If a needed to be destroyed before b , then b would contain an invalid element reference. By destroying objects in the reverse order in which they were created, we guarantee the correct destruction.

+7
Feb 12 '10 at 19:04
source share

Yes and yes. The order of destruction is always the opposite of the order of construction, for member variables.

+5
Feb 12 2018-10-12
source share



All Articles