gpt4 book ai didi

c++ - 使用 static_cast(或 reinterpret_cast)进行不添加成员的继承的无效向下转换的安全性

转载 作者:太空狗 更新时间:2023-10-29 20:41:26 24 4
gpt4 key购买 nike

我想知道标准对以下代码的安全性有何看法:

class A { int v; };
class B: public A { }; // no added data member

A a;
B& b = static_cast<B&>(a);

显然 a 的运行时类型是 A,而不是 B,因此转换并不是真正的类型安全。但是,由于没有添加任何成员并且没有任何东西是虚拟的,IMO 类的内存布局应该是相同的并且这应该可以工作(也许编写 reinterpret_cast 来指示这种行为会更好?) .我的猜测是这是 UB,但可以与任何编译器一起使用。还是这实际上定义明确?或者更危险?

此外,如果 B 有一些额外的非虚拟成员方法,会有什么改变吗?同样,直觉上我会说不,但我想知道标准对此有何看法。

最佳答案

无论是否有虚函数,都是未定义的行为。标准说的很清楚,

If the prvalue of type "pointer to cv1 B" points to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the result of the cast is undefined.

关于c++ - 使用 static_cast(或 reinterpret_cast)进行不添加成员的继承的无效向下转换的安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21372117/

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