"Eric" <sh*****@yahoo.com> wrote in message
news:41********@news.bezeqint.net...
"John Harrison" <jo*************@hotmail.com> wrote in message
news:30*************@uni-berlin.de...
"Eric" <sh*****@yahoo.com> wrote in message
news:41********@news.bezeqint.net... >I found the following phenomenon in VC++ 2005:
>
> struct A {};
>
> struct B : public A
> {
> virtual ~B() {}
> };
>
> A* p = new B;
> delete p; // crashes when executing this line
>
> Does anyone have any insight into why it is crashing there?
>
Because C++ says that this is undefined behaviour. If you delete a
derived
class though a base class pointer then the base class *must* have a
virtual destructor.
I had thought that what would happen is that the derived class destructor
would not be called but I see you're right about the standard saying the
behavior is undefined. If I make B::~B non-virtual then it runs ok and
B::~B
is not called.. However making B::~B virtual causes it to crash.
Is there any simple explanation of this particular implementation
mechanism
that causes it to crash when B::~B is made virtual?
B contains a vtable, A does not. Therefore the A object embedded in the B
object is offset four bytes from the start of the whole object. Therefore
when you say delete p you are passing a pointer to the deallocation routine
that is different from the pointer that was allocated. At least that seems
to be what is happening on my platform. I bet if you add any virtual
function to A (not a destructor) it will no longer crash. Would still
technically be undefined behaviour of course.
Try this code, with and without the dummy function.
#include <iostream>
using namespace std;
class A
{
//virtual void dummy() {}
};
class B : public A
{
public:
virtual ~B() {}
};
int main()
{
B* b = new B();
A* a = b;
cout << "a = " << a << '\n';
cout << "b = " << b << '\n';
delete a;
}
john