How do I use =default and =delete in C++?

In C++, the `=default` and `=delete` specifiers are used to explicitly control the default behavior of special member functions. These features help developers enforce certain constraints or behaviors in their classes.

=default

The `=default` specifier is used to indicate that the compiler should generate the default implementation of a special member function, such as a constructor, destructor, or copy/move constructor/assignment operator. This can be useful when you want to mark a function as explicitly defaulted, making your intentions clear without manually implementing the function.

Example of =default

class MyClass { public: MyClass() = default; // Default constructor MyClass(const MyClass&) = default; // Copy constructor MyClass& operator=(const MyClass&) = default; // Copy assignment operator ~MyClass() = default; // Destructor };

=delete

The `=delete` specifier allows you to explicitly delete a member function to prevent its usage. This can be handy for functions that should not be allowed, such as copy constructors in classes that manage resources (to enforce unique ownership).

Example of =delete

class NonCopyable { public: NonCopyable() = default; NonCopyable(const NonCopyable&) = delete; // Delete copy constructor NonCopyable& operator=(const NonCopyable&) = delete; // Delete copy assignment operator };

=default =delete C++ special member functions constructors destructors