如果派生类是多态的,是否可以static_cast基类构造函数中的派生类指针?

Can you static_cast to derived class pointer in base class constructor, if the derived class is polymorphic?

提问人:Yksisarvinen 提问时间:11/17/2023 最后编辑:Yksisarvinen 更新时间:11/19/2023 访问量:112

问:

想象一下以下具有 CRTP 和多态性的代码:

template <typename Derived>
class CRTP {
   public:
   // in real code, the result of this cast is saved in another class 
    CRTP() { static_cast<Derived*>(this); }
};

class MyClass : public CRTP<MyClass> {
    virtual void foo(){};
};

int main() { 
    MyClass m; 
}

阅读后,您能否将“this”static_cast到基类构造函数中的派生类,然后稍后使用结果? 和标准([expr.static.cast]#12, [basic.life]#6[class.cdtor]),我相信只要指针和引用除了保存到变量之外不使用,这就可以了。但是,UndefinedBehaviourSanitizer 不同意(在 godbolt 上查看):

/app/example.cpp:4:14: runtime error: downcast of address 0x7ffdc5ba6df8 which does not point to an object of type 'MyClass'
0x7ffdc5ba6df8: note: object has invalid vptr
 fd 7f 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  83 00 04 1e ba 7f 00 00  80 8b 20 1e
              ^~~~~~~~~~~~~~~~~~~~~~~
              invalid vptr

如果不是多态的,则错误消失。Derived

它只是UBSan的误报,还是标准中有什么内容可以改变多态类的情况?


作为参考,我的真实代码看起来更像是这样:https://godbolt.org/z/f9sePhv73。我将对该类的引用存储在另一个类中(不在其中使用构造函数),并且还继承了一个使其成为虚拟的 mixin,因此摆脱 vptr 并不太简单。DerivedMyClass

C++ 语言-律师 C++20 UBSAN

评论


答: 暂无答案