c++ - Position of a vpointer in an object -
c++ - Position of a vpointer in an object -
class c { public: c() : m_x(0) { } virtual ~c() { } public: static ptrdiff_t member_offset(const c &c) { const char *p = reinterpret_cast<const char*>(&c); const char *q = reinterpret_cast<const char*>(&c.m_x); homecoming q - p; } private: int m_x; }; int main(void) { c c; std::cout << ((c::member_offset(c) == 0) ? 0 : 1); std::cout << std::endl; std::system("pause"); homecoming 0; }
the programme above outputs 1
. check addresses of c
object , c
's field m_x
. prints out 1
means addresses not equal. guess is because d'tor virtual compiler has create vtable
class , set vpointer
in class's object. if i'm wrong please right me.
apparently, puts vpointer
@ origin of object, pushing m_x
field farther , giving different address. case? if standard specify vpointer
's position in object? according wiki it's implementation-dependent. , position may alter output of program.
so can predict output of programme without specifying target platform?
there no "vpointers" in c++. implementation of polymorphism , dynamic dispatch left compiler, , resulting class layout not in way specified. object of polymorphic type have carry some state in order identify concrete type when given view of base of operations subobject.
implementations vtables , vptrs mutual , popular, , putting vptr @ origin of class means don't need pointer adjustments single inheritance , downcasts.
many c++ compilers follow (parts of) itanium abi c++, specifies class layout decisions this. popular article may provide insights.
c++ pointers memory-address vtable
Comments
Post a Comment