language lawyer - Accessing base class members with incorrect downcast in C++ -
is following c++ code correct?
struct base { int x; }; struct derived : base { int y; } base * b = new base; derived * d = static_cast<derived *>(b); //below access d->x, not d->y std::cout << d->x;
if not, wrong? c++ standard this? @ least have not seen ever crashed.
this reasonably straightforward in [expr.static.cast]/11 (emphasis mine):
a prvalue of type “pointer cv1 b”, b class type, can converted prvalue of type “pointer cv2 d”, d class derived b, if cv2 same cv-qualification as, or greater cv-qualification than, cv1. if b virtual base class of d or base class of virtual base class of d, or if no valid standard conversion “pointer d” “pointer b” exists ([conv.ptr]), program ill-formed. null pointer value converted null pointer value of destination type. if prvalue of type “pointer cv1 b” points b subobject of object of type d, resulting pointer points enclosing object of type d. otherwise, behavior undefined.
you don't have subobject of derived
, it's undefined behaviour.
note there no special cases lvalue or xvalue pointers, , /8 mentions operand undergoes lvalue-to-rvalue conversion.
Comments
Post a Comment