16

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:

  1. Can this be classified as an undefined behavior (we are aware that ~D() is not going to be called for sure)?
  2. What if ~D() is empty. Will it affect the code in any way?
  3. Upon using new[]/delete[] with B* p;, the ~D() will certainly not get called, irrespective of virtualness of the destructor. Is it an undefined behavior or well defined behavior?
j0k
  • 22,600
  • 28
  • 79
  • 90
iammilind
  • 68,093
  • 33
  • 169
  • 336
  • 1
    I often thought of asking the same thing. I'd like a comprehensive answer considering the three cases: (1) B has no virtual methods, (2) B has a virtual method, but a non-virtual destructor, (3). B has a virtual destructor. Apparently, only the latter is well-defined: http://stackoverflow.com/questions/2065938/virtual-destructor – Aaron McDaid Dec 22 '11 at 03:56
  • Refer here regarding the third point: https://stackoverflow.com/questions/6171814/why-is-it-undefined-behavior-to-delete-an-array-of-derived-objects-via-a-base – Hari Mar 08 '23 at 13:54

4 Answers4

20

when/why should I use a virtual destructor?
Follow Herb Sutters guideline:

A base class destructor should be either public and virtual, or protected and nonvirtual

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:

The delete-expression operator destroys a most derived object (1.8) or array created by a new-expression.
delete-expression:
::opt delete cast-expression
::opt delete [ ] cast-expression

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. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.73)

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]

behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements. Undefined behavior may also be expected when this International Standard omits the description of any explicit definition of behavior. [Note: permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed. ]

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.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • +1 for the std::quotes; but I still don't understand, why standard puts it as UB. Since it's guaranteed that `~D()` is not going to be called. Guaranteed behaviors are UB ? – iammilind Dec 22 '11 at 04:15
  • 3
    @iammilind: *Since it's guaranteed that ~D() is not going to be called*, says who? Standard only states if destructor is not virtual then it is UB, the destructor not being called is an after effect in **most of the implementations** and it is not gauranteed, nor required by the standard. – Alok Save Dec 22 '11 at 04:17
  • 3
    @iammilind Nowhere is it guaranteed that `~D()` is not called. The standard says it's *undefined* what happens in this case and that could include the compiler somehow inserting magic to make `~D()` get called! It only follows from a v-table implementation that in most compilers the derived destructor won't be called. – Mark B Dec 22 '11 at 05:05
  • 2
    note: 5.3.5/3 remains essentially unchanged in C++11 and C++14, so this answer is still correct. – M.M Jun 08 '15 at 04:38
  • Er...is this really undefined in the "nasal demons" sense? Is it possible that it might cause something *worse* than partial-deletion of the derived type? – Kyle Strand Aug 21 '15 at 03:10
  • 1
    @KyleStrand there are no degrees of undefined-ness – M.M Nov 03 '16 at 09:43
  • @M.M In terms of the standard, sure. But there are other considerations: what do particular implementations guarantee (e.g. in compiler manuals)? What do particular implementations actually do in practice? What kind of erroneous behavior is even *possible*, logically speaking (regardless of what the standard says)? After posting that comment, I went on to ask [this question](http://stackoverflow.com/q/32132058/1858225), which in fact received a reasonable answer. – Kyle Strand Nov 03 '16 at 16:29
7
  1. Undefined Behavior
  2. (One first note, these deconstructors are generally not as empty as you would think. You still have to deconstruct all of your members) Even if the deconstructor is truly empty(POD?), then it still depends on your compiler. It is undefined by the standard. For all the standard cares your computer could blow up on the delete.
  3. Undefined Behavior

There really is no reason for a non-virtual public destructor in a class that is meant to be inherited from. Look at this article, Guideline #4.

Use either a protected non-virtual destructor and shared_ptrs(they have static linking), or a public virtual destructor.

  • Why it's *undefined* ... Isn't it *well defined* that destructor is not going to be called for sure ? – iammilind Dec 22 '11 at 03:56
  • I guess you could rely on the fact that it does not call D. But unless D is practically an empty class I am fairly sure this is going to cause problems as D's member's do not get deconstructor calls. –  Dec 22 '11 at 03:59
  • 1
    True. But my question is, everything will happen **as expected** like, `~D()` is not called, destructor for members of `~D()` are not called and so on... Where the undefined thing comes ? – iammilind Dec 22 '11 at 04:01
  • Based off the standard, as mentioned in [this](http://stackoverflow.com/questions/2065938/virtual-destructor) wonderful answer. –  Dec 22 '11 at 04:04
2

As reaffirmed by others this is totally undefined because the Base's destructor is not virtual, and no statements can be made by anybody. See this thread for a reference to the standard and further discussion.

(Of course, individual compilers are entitled to make certain promises, but I haven't heard anything about that in this case.)

I find it interesting though, that in this case I think that malloc and free are better defined in some cases than new and delete. Perhaps we should be using those instead :-)

Given a base class and a derived class, neither of which have any virtual methods, the following is defined:

Base * ptr = (Base*) malloc(sizeof(Derived)); // No virtual methods anywhere
free(ptr); // well-defined

You might get a memory leak if D had complex extra members, but apart from this is is defined behaviour.

Community
  • 1
  • 1
Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88
  • I think delete might be well defined for things like PODs. Time to go standard diving. –  Dec 22 '11 at 04:09
  • @EthanSteinberg, The example over on that other thread [link again](http://stackoverflow.com/a/2065961/146041) was based on PODs, as far as my understanding goes. (Actually, if a struct has only non-virtual functions, can it still be called a POD?) – Aaron McDaid Dec 22 '11 at 04:12
  • Yeah, but I heard the new C++ standard did quite a bit of work in revising what a POD was, but it turns out I was wrong. The wording is still the same, just as undefined as before. –  Dec 22 '11 at 04:18
  • `malloc` is an **allocation** function. C has only allocation, but C++ has two orthogonal notions of allocation and *construction*. – Kerrek SB Dec 22 '11 at 04:22
  • 1
    @KerrekSB, Yes, the code I gave does require the user to more explicitly manage initialization. But it does give a route to better-defined behaviour within C++. I'm not really proposing anyone actually use it, but it's an interesting observation. – Aaron McDaid Dec 22 '11 at 04:32
0

(I think I might delete my other answer.)

Everything about that behaviour is undefined. If you want better defined behaviour, you should look into shared_ptr, or implement something similar yourself. The following is defined behaviour, regardless of the virtual-ness of anything:

    shared_ptr<B> p(new D);
    p.reset(); // To release the object (calling delete), as it's the last pointer.

The main trick of shared_ptr is the templated constructor.

Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88