Safety of invalid downcast using static_cast (or reinterpret_cast) for inheritance without added members

為{幸葍}努か 提交于 2019-11-30 18:55:14

问题


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);

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?

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.


回答1:


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

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.



来源:https://stackoverflow.com/questions/21372117/safety-of-invalid-downcast-using-static-cast-or-reinterpret-cast-for-inheritan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!