C ++:构造和初始化顺序保证 [英] C++: Construction and initialization order guarantees

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

问题描述

我对C ++中的构造和初始化顺序保证有一些疑问。例如,下面的代码有四个类 X Y Z W 。主函数实例化一个 class X 的对象,该对象包含 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;
}

编辑:这是否正确? >

edit: Is this correct?

   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.

需要传递到 X 的构造函数,因此它是在构造之前构造的。c $ c> W 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 ++:构造和初始化顺序保证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆