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.

有帮助吗?

解决方案

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.

其他提示

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

In the C++ object model, a type which satisfies the concept of Trivially Copyable is logically one who's data is just a block of bits. The type is just a collection of fundamental data objects with some value(s). As such, copying a block of bits to some storage is a perfectly valid operation, and that storage should (if appropriately aligned) now contain such an object. Furthermore, it's perfectly reasonable to copy a block of bits to some temporary storage (regardless of alignment) and then copy it back into an object of the appropriate type.

C++ allows all of this for Trivially Copyable types.

If a type really is just a block of bits... why should its destruction involve anything more than just memory deallocation? Or more importantly, if its destruction does need to do more than deallocate memory, is it really just a block of bits?

C++'s answer is no, it is not. Or rather, we cannot prove that it isn't just a block of bits.

That's the thing about Trivial Copyability rules: it's all about proof. Under trivial copyability rules, we can prove that such a type is just a block of bits. Other types might be blocks of bits, depending on what those functions do. But since we cannot prove whether they are or not, we therefore forbid treating them as such.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top