Trivial Class vs Aggregate Structure
Trivial Class
A trivial class is a class that:
- Has a trivial default constructor.
- Has a trivial copy constructor.
- Has a trivial move constructor (since C++11).
- Has a trivial copy assignment operator.
- Has a trivial move assignment operator (since C++11).
- Has a trivial destructor.
- Has no virtual functions or virtual base classes.
The trivial constructors/operations/destructor means they are not user-provided (i.e., is implicitly-defined or defaulted on its first declaration).
Trivial classes are basically those that allow bit-wise copy. The operations on these classes are expected to be fast because they can be replaced with simple memory operations like memcpy
or memcmp
.
Aggregate Structure
An aggregate is arrays or a class (typically a struct, but possibly a class as well) that:
- Has no user-declared constructors.
- Has no private or protected non-static data members.
- Has no virtual functions.
- Has no virtual, private, or protected base classes.
- Has no user-defined destructor.
Property | Trivial Class | Aggregate Structure | Notes |
---|---|---|---|
User-Declared Constructors | Allowed | Not Allowed | Aggregate cannot have user-declared constructors. |
Private/Protected Data Members | Allowed | Not Allowed | Aggregates can’t have private or protected non-static members. |
Virtual Functions | Not Allowed | Not Allowed | Neither can have virtual functions. |
Virtual, Private, Protected Bases | Not Allowed | Not Allowed | Neither can have these types of base classes. |
User-Defined Destructor | Allowed | Not Allowed | Aggregate cannot have a user-defined destructor. |
Bitwise Copy-able | Yes | Yes | Both can usually be copied using memcpy. |
Aggregate Initialization | Sometimes | Yes | Only if the trivial class is also an aggregate. |
Allows Optimizations | Yes | Yes | Both allow for various compiler optimizations. |
Reference
https://en.cppreference.com/w/cpp/language/classes
https://en.cppreference.com/w/cpp/language/aggregate_initialization