gpt4 book ai didi

c++ - 将指向部分构造对象的指针转换为指向基类的指针是否合法?

转载 作者:行者123 更新时间:2023-12-04 11:56:32 24 4
gpt4 key购买 nike

也就是说,这样的事情总是合法的吗?

struct Derived;
struct Base { Base(Derived*); };
struct Derived : Base { Derived() : Base(this) { } };
Base::Base(Derived *self) {
if(static_cast<Base*>(self) != this) std::terminate();
}

int main() {
Derived d; // is this well-defined to never call terminate?
}
在这一点上 static_cast被评估, self尚未指向 Derived对象——该对象正在构建中。例如。如果 Derived有数据成员,它们的构造函数就不会被调用。是否仍保证强制转换为已定义行为,从而产生等效于 Base 的指针?的 this (它指向一个完全构造的 Base 基类子对象)?
我认为接近回答这个问题的标准报价是 [conv.ptr]/3 .

...The result of the conversion is a pointer to the base class subobject of the derived class object. ...


但我认为还没有派生类对象,那会发生什么?如果确实未定义, self != static_cast<Derived*>(this) 的答案是否会发生变化? ?
(Clang 和 GCC 编译并“按预期”运行。)

最佳答案

这很好: [class.cdtor]/3

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. ...


它要求源类型(以及从目标类型继承的任何其他基类)具有 开始 它的构造函数并没有完成它的析构函数。甚至基类的初始化器也算作派生构造函数的开始;该标准包含一个非常相似的例子。

关于c++ - 将指向部分构造对象的指针转换为指向基类的指针是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68688892/

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