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++:构造和初始化顺序保证
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01