Understanding the Difference between "=default" and "{}" for Default Constructor and Destructor
While "=default" and "{}" might appear interchangeable for default constructors and destructors, there are key distinctions when considering non-virtual destructors and constructors.
Non-Virtual Destructors
When dealing with non-virtual destructors, the "=default" syntax plays a significant role. It instructs the compiler to automatically generate the destructor as it would for trivial classes, making the type considered trivial. On the other hand, "{}" creates a user-provided destructor, altering the triviality status of the class.
Non-Virtual Constructors
Similarly, for non-virtual constructors, using "=default" allows the compiler to generate a default constructor, maintaining triviality. However, "{}" specifies a user-provided constructor, potentially impacting the class's triviality.
Trivial Classes
In C 11, a trivial class is one that doesn't have any user-provided special member functions (default constructor, copy/move constructors/assignment, destructors). These functions are automatically generated, allowing optimizations like memcpy to be applied.
Example
Consider the following code:
struct Trivial { int foo; }; struct NotTrivial { int foo; NotTrivial() {} }; struct Trivial2 { int foo; Trivial2() = default; };
Conclusion
While "=default" and "{}" may seem similar, they can have substantial implications for the triviality of classes when used with non-virtual destructors or constructors. "=default" retains the compiler's default behavior and preserves triviality, while "{}" creates user-provided functions and potentially alters the class's triviality status.
The above is the detailed content of What's the Difference Between '=default' and '{}' for Default Constructors and Destructors in C ?. For more information, please follow other related articles on the PHP Chinese website!