C++:构造和初始化顺序保证

C++: Construction and initialization order guarantees(C++:构造和初始化顺序保证)

本文介绍了C++:构造和初始化顺序保证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C++ 中的构造和初始化顺序保证有一些疑问.例如,下面的代码有四个类XYZW.main函数实例化了一个class X的对象,其中包含了一个class Y的对象,并且派生自class Z,所以两个构造函数都是叫.另外,传递给X的构造函数的const char*参数会隐式转换为class W的对象,所以W 的构造函数也必须被调用.

I have some doubts about construction and initialization order guarantees in C++. For instance, the following code has four classes X, Y, Z and W. The main function instantiates an object of class X, which contains an object of class Y, and derives from class Z, so both constructors will be called. Additionally, the const char* parameter passed to X's constructor will be implicitly converted to an object of class W, so W's constructor must also be called.

C++ 标准对复制构造函数的调用顺序有哪些保证?或者,等价的,这个程序可以打印什么?

What are the guarantees the C++ standard gives on the order of the calls to the copy constructors? Or, equivalently, what this program is allowed to print?

#include <iostream>

class Z {
   public:
   Z() { std::cout << "Z" << std::endl; }
};

class Y {
   public:
   Y() { std::cout << "Y" << std::endl; }
};

class W {
   public:
   W(const char*) { std::cout << "W" << std::endl; }
};

class X : public Z {
   public:
   X(const W&) { std::cout << "X" << std::endl; }
   private:
   Y y;
};

int main(int, char*[]) {
   X x("x");
   return 0;
}

这是正确的吗?

   W      |
 /       |
Z     Y   |
    /    |
   X      V

推荐答案

在所有类中的构造顺序是有保证的:基类,从左到右指定,后跟成员变量,按照类定义中声明的顺序.类的构造函数体在其所有基类和成员的构造完成后执行.

In all classes construction order is guaranteed: base classes, as specified from left to right followed by member variables in the order declared in the class definition. A class's constructor body is executed once all of its bases' and members' constructions have completed.

在您的示例中 X 派生自 Z 并包含 Y 所以 Z 基础对象首先被构造,然后是Y成员y,然后X的构建完成,X的构造函数的执行身体.

In your example X is derived from Z and contains Y so the Z base object is constructed first, then the Y member y, then the construction of the X completes with the execution of X's constructor body.

临时W需要传递给X的构造函数,所以它在x的构造开始之前被构造,并且将x 初始化完成后销毁.

The temporary W is needed to pass to the constructor of X, so it is constructed before the construction of the x begins and will be destroyed once the initialization of x completes.

所以程序必须打印:

W
Z
Y
X

这篇关于C++:构造和初始化顺序保证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++:构造和初始化顺序保证

基础教程推荐