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

前端 未结 1 705
陌清茗
陌清茗 2021-01-06 06:09

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&         


        
相关标签:
1条回答
  • 2021-01-06 06:43

    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.

    0 讨论(0)
提交回复
热议问题