C++ Special Member Function Guidelines

klaussilveira1 pts0 comments

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 = defaulted, = deleted, 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.<br>When in doubt, do what normal does (rule of zero).

class normal<br>public:<br>normal(); // if it makes sense<br>~normal() = default;

normal(const normal&) = default;<br>normal(normal&&) = default;

normal& operator=(const normal&) = default;<br>normal& operator=(normal&&) = default;<br>};

class immoveable<br>public:<br>immoveable(); // if it makes sense<br>~immoveable() = default;

immoveable(const immoveable&) = delete;<br>immoveable& operator=(const immoveable&) = delete;

immoveable(immoveable&&) = delete;<br>immoveable& operator=(immoveable&&) = delete;<br>};

class container<br>public:<br>container() noexcept;<br>~container() noexcept;

container(const container& other);<br>container(container&& other) noexcept;

container& operator=(const container& other);<br>container& operator=(container&& other) noexcept;<br>};

class resource_handle<br>public:<br>resource_handle() noexcept;<br>~resource_handle() noexcept;

resource_handle(const resource_handle&) = delete;<br>resource_handle& operator=(const resource_handle&) = delete;

resource_handle(resource_handle&& other) noexcept;<br>resource_handle& operator=(resource_handle&& other) noexcept;<br>};

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

normal immoveable container resource_handle const operator

Related Articles