Skip to content

Instantly share code, notes, and snippets.

@char-1ee
Last active April 9, 2024 03:30
Show Gist options
  • Save char-1ee/910592e363cef867c74fc84affe57d59 to your computer and use it in GitHub Desktop.
Save char-1ee/910592e363cef867c74fc84affe57d59 to your computer and use it in GitHub Desktop.

What is Rule of Three in C++?

If you need to explicitly declare either

  • the destructor,
  • copy constructor,
  • copy assignment operator

yourself, you probably need to explicitly declare all three of them.

What is Rule of Five in C++11?

From C++11 on, an object has 2 extra special member functions: the move constructor and move assignment.

class person {
private:
    std::string name;
    int age;

public:
    person(const std::string& name, int age);        // Ctor
    person(const person &) = default;                // 1/5: Copy Ctor
    person(person &&) noexcept = default;            // 4/5: Move Ctor
    person& operator=(const person &) = default;     // 2/5: Copy Assignment
    person& operator=(person &&) noexcept = default; // 5/5: Move Assignment
    ~person() noexcept = default;                    // 3/5: Dtor
}; 

What is Rule of Zero?

The rule of 3/5 is also referred to as the rule of 0/3/5. The zero part of the rule states that you are allowed to not write any of the special member functions when creating your class.

Conclusion

To avoid the concerns about the rule of 0/3/5, using tools provided by the standard library like: std::vector, std::string, std::unique_ptr and std::shared_ptr, effectively removing the need for custom destructors, move/copy constructors, move/copy assignment and default constructors.

Here is an example:

class A {
private:
    std::string brandname;
    std::unique_ptr<B> b;
    std::vector<B> vec;
public:
    virtual void something(){} = 0;
};

rather than

class A {
private:
    char *brandname;
    B* b; 
    vector<B*> vec; 
public:
    ~Account()
    {
        delete [] brandname;
        delete b;
    };
    something(){} = 0; //virtual function (reason #1: base class)
}

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment