What are non trivial destructors in C++ used for

3 weeks ago 13
ARTICLE AD BOX

Oersted's answer explains how a class that manages memory has to release it in its destructor. TobySpeight's answer explains that memory is not the only resource that a destructor has to free. There are much simpler cases of non-trivial destructors.

Its probably a matter of wording in your question that you ask for "non-trivial destructor", but I think its worth to explain the difference between a non-trivial destructor and the need to write a custom destructor.


First I want to refer you to What is a non-trivial destructor in C++? where the accepted answer explains:

The rule is very straight-forward: Does your class have an explicit destructor? If yes, you're non-trivial. If no, check each non-static member object; if any of them are non-trivial, then you're non-trivial.

And cppreference:

The destructor for class T is trivial if all following conditions are satisfied:

[...]

Every non-static data member of class type (or array of class type) has a trivial destructor. (until c++26)

[...]

A trivial destructor is a destructor that performs no action.

(The change since c++26 is not important for the point I am trying to make here)


Now consider std::vector. It manages a dynamically allocated array. That array is destroyed in the vectors destructor much like in @Oersted's example. Further, consider you have a std::vector member:

#include <vector> #include <iostream> #include <type_traits> struct foo { std::vector<int> bar; }; int main() { std::cout << std::is_trivially_destructible_v<foo>; }

We could define a destructor with an empty body: ~foo() {}. In any case, after the body of that destructor is executed the members have to be destroyed. This is done automatically even if foo does not declare a destructor. foos destructor is not trivial, because std::vectors destructor is not trivial.


Most of the time you want to follow the rule of 0. It is applicable when the class itself does not manage a resource and it implies that you do not have to write a destructor. That, however, does not imply that any rule of 0 class has a trivial destructor.

The takeaway is that (non-trivial) destructors are needed to clean up memory of members, or generally any resource that the class or its members acquired. Even in cases where you do not have to write a destructor, it is still there and does any clean up that is necessary before the objects memory can be wiped out.

Read Entire Article