c++ - memory layout of class hierarchy -


my target create instances of classes of class hierarchy share common data. create ( union ) enough memory biggest instance can created @ allocated memory. want create / exchange instance of class , use "old" data @ memory there. valid/legal operation?

the original code uses mtp stuff create union , target use class hierarchy core of state machine implementation. show basic code here contains problem.

i saw problem if base class did not contain virtual methods derived ones did. because vtable-pointer goes in front of memory ( gcc on x86/linux).

simple question: can instance of derived class access data base class if instance of base class created before , memory reused instance of derived class?

class base {     public:         int a;         base()=default;         base( int _a):a(_a){}          void print() { cout << "value: " << << endl; } };  class derived1: public base {     public:         int d;          derived1(): d( 0x11223344){} };  union  u {        u(){}     base base;     derived1 derived1; } u;  int main() {     memset( &u, 0, sizeof(u));      new (&u) base(12345678);     u.base.print();      new (&u) derived1;     u.base.print();  } 

no won't work because sandard says:

9.5/1 : in union, @ 1 of non-static data members can active @ time is, value of @ 1 of non-static data members can stored in union @ time.

what try undefined behaviour:

new (&u) derived1;  // risky !!! 

with placement new overwrite object in u before, without destroying correctly. creation of derived1 anyway create own base. if somehow manage keep old values in memory, it's still undefined behaviour: work or not, depending on object layout , implemetnation of compiler.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -