Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between virtual destructor=default and one with empty body?

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?

like image 724
Ruslan Avatar asked Jul 03 '17 13:07

Ruslan


People also ask

Can destructor be empty?

Since no destructor is defined, a C++ compiler should create one automatically for class Foo . If the destructor does not need to clean up any dynamically allocated memory (that is, we could reasonably rely on the destructor the compiler gives us), will defining an empty destructor, ie.

Is the default destructor virtual?

The destructor is not user-provided (meaning, it is either implicitly declared, or explicitly defined as defaulted on its first declaration) The destructor is not virtual (that is, the base class destructor is not virtual) All direct base classes have trivial destructors.

Is there a default destructor?

The default destructor calls the destructors of the base class and members of the derived class. The destructors of base classes and members are called in the reverse order of the completion of their constructor: The destructor for a class object is called before destructors for members and bases are called.

What is the difference between a virtual destructor and normal destructor?

A normal destructor is set to be just that a normal destructor that the class has implementation for and nowhere else. A virtual destructor can be customized for the task at hand because it can be overriden. So if anywhere you need to change the behavior of the destructor you should make it virtual.


1 Answers

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.

like image 76
midor Avatar answered Oct 22 '22 14:10

midor