...

/

Default Move Semantics and the Rule of Zero

Default Move Semantics and the Rule of Zero

Learn about the automatically generated copy-assignment operator.

As with the copy-constructor and copy-assignment, the move-constructor and move-assignment can be generated by the compiler. Although some compilers allow themselves to automatically generate these functions under certain conditions, we can simply force the compiler to generate them by using the default keyword.

In the case of the Button class, which doesn't manually handle any resources, we can simply extend it like this:

Press + to interact
class Button {
public:
Button() {} // Same as before
// Copy-constructor
//copy-assignment
Button(const Button&) = default;
auto operator=(const Button&) -> Button& = default;
// Move-constructor
//move-assignment
Button(Button&&) noexcept = default;
auto operator=(Button&&) noexcept -> Button& = default;
// Destructor
~Button() = default;
// ...
};

To make it even simpler, if we do not declare any custom copy-constructor/copy-assignment or destructor, the move-constructors/move-assignments are implicitly declared, meaning that the first Button class actually handles everything:

Press + to interact
class Button {
public:
Button() {} // Same as before
// Nothing here, the compiler generates everything automatically!
// ...
};

It's easy to forget that adding just ...