Invalid downcast security using static_cast (or reinterpret_cast) to inherit without adding members

I was wondering what the security standard says for 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 execution type is a - a , not B , so overlapping is not type safe. However, since no member was added, and nothing was virtual, IMO, the class memory layout should be the same and this should work (maybe it would be better to write reinterpret_cast to indicate this behavior?). I assume this is UB, but will work with any compiler. Or is it really well defined? Or is it quite 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 it.

+3
source share
1 answer

This behavior is undefined, regardless of whether a virtual function exists or not. The standard clearly says

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

+5
source

Source: https://habr.com/ru/post/983505/


All Articles