Virtual destructor and undefined behavior
Asked Answered
T

4

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?
Tollhouse answered 22/12, 2011 at 3:46 Comment(2)
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: https://mcmap.net/q/570386/-virtual-destructor-is-it-required-when-not-dynamically-allocated-memoryTragus
Refer here regarding the third point: #6172314Beamon
Q
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.

Quenby answered 22/12, 2011 at 4:10 Comment(7)
+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 ?Tollhouse
@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.Quenby
@Tollhouse 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.Memoirs
note: 5.3.5/3 remains essentially unchanged in C++11 and C++14, so this answer is still correct.Zwolle
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?Actium
@KyleStrand there are no degrees of undefined-nessZwolle
@Zwolle 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, which in fact received a reasonable answer.Actium
D
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.

Discernible answered 22/12, 2011 at 3:53 Comment(4)
Why it's undefined ... Isn't it well defined that destructor is not going to be called for sure ?Tollhouse
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.Discernible
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 ?Tollhouse
Based off the standard, as mentioned in this wonderful answer.Discernible
T
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.

Tragus answered 22/12, 2011 at 4:7 Comment(5)
I think delete might be well defined for things like PODs. Time to go standard diving.Discernible
@EthanSteinberg, The example over on that other thread link again 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?)Tragus
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.Discernible
malloc is an allocation function. C has only allocation, but C++ has two orthogonal notions of allocation and construction.Corley
@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.Tragus
T
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.

Tragus answered 22/12, 2011 at 4:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.