inheritance - Does this C++ program invoke undefined behavior? -
i reading static_cast operator.
consider following example:
#include <iostream> class b { }; class d : public b { public: void fun() { std::cout<<"fun() called\n"; } }; void f(b* pb,d* pd) { d* pd2=static_cast<d*>(pb); b* pb2=static_cast<b*>(pd); pd2->fun(); } int main() { b b; d d; f(&b,&d); }
it says that:
in example follows, line d* pd2 = static_cast(pb); not safe because d can have fields , methods not in b. however, line b* pb2 = static_cast(pd); safe conversion because d contains of b.
in contrast dynamic_cast, no run-time check made on static_cast conversion of pb. object pointed pb may not object of type d, in case use of *pd2 disastrous. instance, calling function member of d class, not b class, result in access violation.
i tried on gcc 4.8.1 & msvs 2010 & output fun() called. program invoke undefined behavior? can program crash @ runtime? c++ standard says this? please correct me if understood incorrectly.
yes, of course is.
you invoking member function of d
on object that's b
, forcing conversion b*
d*
.
it "appears work" because function involved not attempt access actual data and, therefore, there no memory access computer notice , complain @ runtime.
in fact, don't need bother talking whether function call has undefined behaviour; cast bad enough:
[c++14: 5.4.9/11]:
a prvalue of type “pointer cv1b
,”b
class type, can converted prvalue of type “pointer cv2d
,”d
class derived (clause 10)b
, if valid standard conversion “pointerd
” “pointerb
” exists (4.10), cv2 same cv-qualification as, or greater cv-qualification than, cv1, ,b
neither virtual base class ofd
nor base class of virtual base class ofd
. null pointer value (4.10) converted null pointer value of destination type. if prvalue of type “pointer cv1b
” pointsb
subobject of object of typed
, resulting pointer points enclosing object of typed
. otherwise, behavior undefined.
Comments
Post a Comment