Code failure when the destructor of the derived class virtual and base class dtor does not

I tried the following code on gcc 4.4.5.

If the participant’s “data” is missing, the code executes a penalty, but in his presence it fails. It also fails when the dtor derived class is not virtual.

I know that the behavior will be Undefined, as indicated in C ++ 03 (5.3.5 / 3) in both cases, but still can someone give me some explanation why this happens in the latter case?

And yes, I know that UB means that something can happen, but still I would like to know the details specific to the implementation.

#include<iostream>    
using std::cout;

struct base{
int data;
   base(){
      cout << "ctor of base\n";
   }
   ~base(){
      cout << "dtor of base\n";
   }
};

struct derived :  base{
   derived(){
      cout << "ctor of derived\n";
   }
   virtual ~derived(){
      cout << "dtor of derived\n";
   }
};

int main(){
   base *p = new derived;
   delete p;
}
+5
2

, (gcc 4.6.0, linux x86_64) , ( data ), , p , derived.

valgrind ,

Address 0x595c048 is 8 bytes inside a block of size 16 alloc'd

, :

derived * d = new derived;
std::cout << d << '\n';
base *p = d;
std::cout << p << '\n';

, gcc {vtable, base, }

, {vtable, base, } {base} , , .

, vtable , , .

+9

, .

pod vtable ( ). , base, derived. , , / .

+2

All Articles