This question is different than ‘When/why should I use a virtual destructor?‘.
struct B {
virtual void foo ();
~B() {} // <--- not virtual
};
struct D : B {
virtual void foo ();
~D() {}
};
B *p = new D;
delete p; // D::~D() is not called
Questions:
- Can this be classified as an undefined behavior (we are aware that
~D()is not going to be called for sure)? - What if
~D()is empty. Will it affect the code in any way? - Upon using
new[]/delete[]withB* p;, the~D()will certainly not
get called, irrespective ofvirtualness of the destructor. Is it
an undefined behavior or well defined behavior?
when/why should I use a virtual destructor?
Follow Herb Sutters guideline:
Can this be classified as an undefined behavior (we are aware that ~D() is not going to be called for sure) ?
It is Undefined Behavior as per the standard, which usually results in the Derived class destructor not being called and resulting in a memory leak, but it is irrelevant to speculate on after effetcs of an Undefined Behavior because standard doesn’t gaurantee anything in this regard.
C++03 Standard: 5.3.5 Delete
5.3.5/1:
5.3.5/3:
What if
~D()is empty. Will it affect the code in any way ?Still it is Undefined Behavior as per the standard, The derived class destructor being empty may just make your program work normally but that is again implementation defined aspect of an particular implementation, technically, it is still an Undefined Behavior.
Note that there is no gaurantee here that not making the derived class destructor virtual just does not result in call to derived class destructor and this assumption is incorrect. As per the Standard all bets are off once you are crossed over in Undefined Behavior land.
Note what he standard says about Undefined Behavior.
The C++03 Standard: 1.3.12 undefined behavior [defns.undefined]
If only derived destructor will be not called is governed by the bold text in the above quote, which is clearly left open for each implementation.