使用static_cast(或reinterpret_cast)进行无效下传的安全性,无需添加成员 [英] Safety of invalid downcast using static_cast (or reinterpret_cast) for inheritance without added members

查看:118
本文介绍了使用static_cast(或reinterpret_cast)进行无效下传的安全性,无需添加成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道下面的代码的安全标准:

I was wondering what the standard says about the safety of the following code:

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,但将与任何编译器工作。或者这是真的很好定义?

Obviously the runtime type of a is A, not B, so the cast is not really type safe. However, since there was no member added and nothing is virtual, IMO the memory layout of the classes should be the same and this should work (maybe it would be nicer to write reinterpret_cast to indicate this behaviour?). My guess would be that this is UB, but would work with any compiler. Or is this actually well defined? Or rather dangerous?

此外,如果 B 有一些额外的非虚拟成员方法,会发生什么变化?再次,直观地,我会说不,但我不知道什么标准有关这个。

Also, would anything change if B had some additional non-virtual member methods? Again, intuitively I would say no, but I wonder what the standard has to say about this.

推荐答案

这是未定义的行为,是否有虚拟功能。标准清楚地表明,

It's undefined behavior, regardless of whether there's virtual function or not. The standard says clearly,


如果类型指向cv1 B的指针的prvalue指向B是
,类型D的对象的子对象,所得指针
指向类型D的包围对象。否则,
cast的结果是未定义的。

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.

这篇关于使用static_cast(或reinterpret_cast)进行无效下传的安全性,无需添加成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆