gpt4 book ai didi

c++ - 在构造期间隐式转换为基类

转载 作者:太空宇宙 更新时间:2023-11-04 11:29:11 24 4
gpt4 key购买 nike

12.7/3中给出了下面的例子:

struct A { };
struct B : virtual A { };
struct C : B { };
struct D : virtual A { D(A*); };
struct X { X(A*); };
struct E : C, D, X {
E() : D(this), // undefined: upcast from E* to A*
// might use path E* → D* → A*
// but D is not constructed
// D((C*)this), // defined:
// E* → C* defined because E() has started
// and C* → A* defined because
// C fully constructed
X(this) { // defined: upon construction of X,
// C/B/D/A sublattice is fully constructed
}
};

示例规则如下:

To explicitly or implicitly convert a pointer (a glvalue) referring to an object of class X to a pointer (reference) to a direct or indirect base class B of X, the construction of X and the construction of all of its direct or indirect bases that directly or indirectly derive from B shall have started and the destruction of these classes shall not have completed, otherwise the conversion results in undefined behavior.

在标准提供的情况下,我们有 A 派生类的列表是 {B, D, C, E}ACB 的构建已经完成。但是 D 的构造在我们需要向上转换使用 E* → D* → A* 的时候已经开始了。那么为什么实际行为未定义?

最佳答案

A* 的转换是一个参数评估,它必须在结果传递给 D 构造函数之前完成。所以D的构建还没有开始。作为反例,E 的构造已经此时开始,尚未完成。

关于c++ - 在构造期间隐式转换为基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25479294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com