Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why trivial copyable class require the destructor must be trivial

Base on the C++ standard. The trivial copyable class are define as following:

According to 9/5,

A trivially copyable class is a class that:
- has no non-trivial copy constructors (12.8),
- has no non-trivial move constructors (12.8),
- has no non-trivial copy assignment operators (13.5.3, 12.8),
- has no non-trivial move assignment operators (13.5.3, 12.8), and
- has a trivial destructor (12.4).

By my understanding, the trivially copyable class is which can be copied by bitwise copied. So what's the intuition and reason to require trivial destructor which is unrelated to the bitwise copy.

like image 885
ZijingWu Avatar asked Sep 03 '25 02:09

ZijingWu


2 Answers

The reason is simple enough. Trivially copyable means that it is valid and defined behaviour to copy one object A over the top of another B. Obviously the destructor for B will not be called, so it has to be trivial.

There is a description of object lifetime at N3797 3.8/4 which appears to cover the situation. However, there could be a loophole regarding reuse of storage and non-calling of non-trivial destructor provided the program does not depend on side effects of the destructor.

like image 94
david.pfx Avatar answered Sep 04 '25 21:09

david.pfx


A non trivial destructor likely implies you are deleting some pointers. If this is the case it seems error prone to do a bitwise copy of the class since you'd then have two instances that will both try to delete the same pointer.

This is just a guess though

like image 28
thisisdog Avatar answered Sep 04 '25 19:09

thisisdog