← Patterns

The rule of zero

123456789101112131415#include <memory> #include <vector> class foo { private: int x = 10; std::vector<int> v = {1, 2, 3, 4, 5}; }; class bar { public: std::unique_ptr<int> p = std::make_unique<int>(5); };

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++98 or newer.

Intent

Utilise the value semantics of existing types to avoid having to implement custom copy and move operations.

Description

The rule of zero states that we can avoid writing any custom copy/move constructors, assignment operators, or destructors by using existing types that support the appropriate copy/move semantics.

The class foo on lines 4–9, for example, does not perform any manual memory management, yet correctly supports copies and moves without any memory leaks. The defaulted copy/move constructors and assignment operators will simply copy or move each member. For the int x (line 7), this will copy its value. For v (line 8), which is a std::vector, all of its elements will be copied over.

The class bar on lines 11–15 is not copyable by default because it has a std::unique_ptr member which itself is not copyable. However, it correctly supports move operations, which will transfer ownership of the dynamically allocated resource.

Contributors

  • Joseph Mansfield

Last Updated

09 December 2017

Source

Fork this pattern on GitHub

Share