Home >Backend Development >C++ >How does the C standard guarantee the order of member constructor and destructor calls in a class with member variables of other classes?
Problem:
In C , when a class contains member variables of other classes, the order of their initialization and destruction is crucial. Consider 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; }
Under the C standard, is it guaranteed that this program will always produce the following output:
A::A B::B C::C C::~ B::~ A::~
Answer:
Yes, it is guaranteed.
According to section 12.6.2 of the C standard, initialization and destruction of members within a class follow specific rules:
In the provided example, the members of the Aggregate struct are declared in the order a, b, and c. Therefore, it is guaranteed that they will be initialized in the order A::A, B::B, and C::C and destroyed in the reverse order C::~, B::~, and A::~.
The above is the detailed content of How does the C standard guarantee the order of member constructor and destructor calls in a class with member variables of other classes?. For more information, please follow other related articles on the PHP Chinese website!