Search code examples
c++virtual-destructor

virtual destructor's practical necessity in a particular case


C++03 5.3.5.3

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.

This is the theory. The question, however, is a practical one. What if the derived class adds no data members?

struct Base{
   //some members
   //no virtual functions, no virtual destructor
};
struct Derived:Base{
   //no more data members
   //possibly some more nonvirtual member functions
};

int main(){
     Base* p = new Derived;
     delete p; //UB according to the quote above
}

The question: is there any existing implementation on which this would really be dangerous? If so, could you please describe how the internals are implemented in that implementation which makes this code crash/leak or whatever? I beg you to believe, I swear that I have no intentions to rely on this behavior :)


Solution

  • One example is if you provide a custom operator new in struct Derived. Obviously calling wrong operator delete will likely produce devastating results.