9

A virtual destructor which does nothing is

virtual ~ClassName() {}

Since C++11 we can alternatively say:

virtual ~ClassName() = default;

Is there any difference between these two?

Ruslan
  • 18,162
  • 8
  • 67
  • 136
  • @Rakete1111: Actually it is not a duplicate, since the other question is about default destructors being public, and this one is about why one would use = default instead of {} in the virtual destructor that is necessary in a base class with virtual member functions. I was wondering the same thing, namely if the compiler can maybe optimize things differently with = default, or if it is simply more idiomatic C++11. It is after all quite a few more characters to type. – Masseman Aug 29 '17 at 14:15
  • @Masseman Yes sure, they are not totally equivalent. But they ask the same question, should I use `{}` or `= default;` for the destructor? It doesn't matter that the destructor is virtual, because that's not what the question is about. – Rakete1111 Aug 29 '17 at 16:09

1 Answers1

6

The main difference is that there are rules for defaulted functions that specify under which circumstances they are deleted (cf. ISO c++14(N4296) 8.4, 12.1, 12.4, 12.8)

8.4.2.5: Explicitly-defaulted functions and implicitly-declared functions are collectively called defaulted functions, and the implementation shall provide implicit definitions for them (12.1 12.4, 12.8), which might mean defining them as deleted.

e.g.:

12.4.5: A defaulted destructor for a class X is defined as deleted if: (5.1) — X is a union-like class that has a variant member with a non-trivial destructor, (5.2) — any potentially constructed subobject has class type M (or array thereof) and M has a deleted destructor or a destructor that is inaccessible from the defaulted destructor, (5.3) — or, for a virtual destructor, lookup of the non-array deallocation function results in an ambiguity or in a function that is deleted or inaccessible from the defaulted destructor

In case your use falls into one of the deleted categories, using default will be equivalent to using delete whereas {} won't be.

midor
  • 5,487
  • 2
  • 23
  • 52