Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top