C++: Construction and initialization order guarantees(C++:构造和初始化顺序保证)
问题描述
我对 C++ 中的构造和初始化顺序保证有一些疑问.例如,下面的代码有四个类X、Y、Z 和W.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++:构造和初始化顺序保证
基础教程推荐
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
