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?

How does the C standard guarantee the order of member constructor and destructor calls in a class with member variables of other classes?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-08 06:31:02509browse

How does the C   standard guarantee the order of member constructor and destructor calls in a class with member variables of other classes?

Order of Member Constructor and Destructor Calls

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:

Initialization Order

  • Virtual base classes (if any) are initialized first, depth-first, left-to-right.
  • Direct base classes are initialized next, in declaration order.
  • Non-static data members are initialized in declaration order, regardless of the order of member initialization.
  • The constructor body is executed last.

Destruction Order

  • Compound-statement of the destructor body is executed first.
  • Non-static data members are destroyed in reverse declaration order.
  • Direct base classes are destroyed in declaration order.
  • Virtual base classes (if any) are destroyed last, in reverse depth-first, left-to-right order.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn