C++ Special Member Function Guidelines
The C++ special member functions are:
- default constructor
- copy constructor
- move constructor
- destructor
- copy assignment
- move assignment
They can be either = default
ed, = delete
d, not manually written at all, or have a custom implementation.
The majority of classes you write will match one of the four options listed below.
When in doubt, do what normal
does (rule of zero).
class normal
{
public:
normal(); // if it makes sense
~normal() = default;
normal(const normal&) = default;
normal(normal&&) = default;
normal& operator=(const normal&) = default;
normal& operator=(normal&&) = default;
};
class immoveable
{
public:
immoveable(); // if it makes sense
~immoveable() = default;
immoveable(const immoveable&) = delete;
immoveable& operator=(const immoveable&) = delete;
immoveable(immoveable&&) = delete;
immoveable& operator=(immoveable&&) = delete;
};
class container
{
public:
container() noexcept;
~container() noexcept;
container(const container& other);
container(container&& other) noexcept;
container& operator=(const container& other);
container& operator=(container&& other) noexcept;
};
class resource_handle
{
public:
resource_handle() noexcept;
~resource_handle() noexcept;
resource_handle(const resource_handle&) = delete;
resource_handle& operator=(const resource_handle&) = delete;
resource_handle(resource_handle&& other) noexcept;
resource_handle& operator=(resource_handle&& other) noexcept;
};
Shown in italics are the effective compiler-generated implementations of the special members; you can write them yourself to be explicit.
Full rationale and further explanations: Tutorial: When to Write Which Special Member