C++构造函数、析构函数执行顺序详解

构造函数执行顺序

  1. 调用虚基类构造函数(如有多个则按虚基类声明顺序从左到右)
  2. 调用基类构造函数(如有多个则按基类声明顺序从左到右)
  3. 设定虚函数表指针值(virtual table pointer)
  4. 执行初始化列表、调用成员变量构造函数(按成员变量声明顺序)
  5. 执行自身构造函数

析构函数执行顺序(与构造函数相反)

  1. 执行自身析构函数
  2. 调用成员变量析构函数(与成员声明顺序相反)
  3. 调整虚函数表指针值
  4. 调用基类析构函数(从右到左)
  5. 调用虚基类析构函数(从右到左)
    // This program demonstrates the order in which base and
    //derived class constructors and destructors are called.
    #include 
    #include 
    using namespace std;
    // Base class
    class BaseDemo
    {
        public:
            BaseDemo() // Constructor
            {
                cout << "This is the BaseDemo constructor. \n";
            }
            virtual ~BaseDemo() // Destructor
            {
                cout << "This is the BaseDemo destructor.\n";
            }
    };
    // Derived class
    class DeriDemo : public BaseDemo
    {
        public:
            DeriDemo() // Constructor
            {
                cout << "This is the DeriDemo constructor.\n";
            }
            virtual ~DeriDemo() // Destructor
            {
                cout << "This is the DeriDemo destructor.\n";
            }
    };
    int main()
    {
        cout << "We will now create a DeriDemo obj ect.\n";
        shared_ptr d = make_shared(); cout << "The program is now going to,end.\n";
        return 0;
    }

程序输出结果:

We will now create a DeriDemo obj ect.
This is the BaseDemo constructor.
This is the DeriDemo constructor.
The program is now going to,end.
This is the DeriDemo destructor.
This is the BaseDemo destructor.

你可能感兴趣的:(c++,c++,开发语言)