i looking @ answer , wondering if casting object first member reinterpret_cast , using result safe in c++.
let's assume have class a, class b , instance b of b:
class a{ public: int i; void foo(){} }; class b{ public: a; }; b b;
question 1: is safe use b.a this: reinterpret_cast<a*>(&b)->foo()
?
note: in general case suppose class , member both standard layout.
my lecture of available references on reinterpret_cast tells me such usage should authorized there no aliasing violation, conflicts many answers this one.
question2: is safe use b.a this: static_cast<a*>(static_cast<void*>(&b))->foo()
?
yes, because both classes here standard-layout types, can convert between &b
, &b.a
.
reinterpret_cast<a*>(p)
defined same static_cast<a*>(static_cast<void*>(p))
, (5.2.10p7) both questions equivalent.
for standard-layout classes, address of struct/class same address of first non-static member (9.2p19). , static_cast
to/from void*
preserve address (5.2.9p13), meaning result valid.
if classes not standard-layout, not rely on behavior.
Comments
Post a Comment