Programs segfault when deleting a pointer which refers to a virtually-derived class

Martin v. Loewis martin@mira.isdn.cs.tu-berlin.de
Tue Nov 30 23:39:00 GMT 1999


>   Hello.  I believe that I've found a g++ bug; however, I'm not sure
> (C++ is a big and hairy language, and I may misunderstand what is
> allowed and what isn't).

Thanks for your bug report. As has been pointed out, it is not a bug
of g++ if the program crashes: the base must have a virtual destructor
if you want polymorphic delete.

To quote the International Standard, 5.3.5, [expr.delete]/3 says

# In the first alternative (delete object), if the static type of the
# operand is different from its dynamic type, the static type shall be
# a base class of the operand's dynamic type and the static type shall
# have a virtual destructor or the behavior is undefined.

Since your code has undefined behaviour, the code might crash, or it
may wake you up at four in the morning...

> A warning is issued already if "ancestor" contains a non-virtual
> destructor, but in this code it doesn't contain a destructor at all.

Yes, there is a documented warning

`-Wnon-virtual-dtor (C++ only)'
     Warn when a class declares a non-virtual destructor that should
     probably be virtual, because it looks like the class will be used
     polymorphically.

What you propose goes beyond that, you require a destructor for all
classes with virtual functions.

I can't see a bug in the compiler here: it behaves as documented, and
according to the relevant standards. If you want to see a new feature
added, please have a look at

http://egcs.cygnus.com/faq.html#support

Regards,
Martin



More information about the Gcc-bugs mailing list