0 votes
in C Plus Plus by
What is The Rule of Four?

1 Answer

0 votes
by

“The Rule of The Big Four (and a half)" states that if you implement one of

  • The copy constructor
  • The assignment operator
  • The move constructor
  • The destructor
  • The swap function

then you must have a policy about the others.

Which functions need to implemented, and what should each function's body look like?

  • default constructor (which could be private)
  • copy constructor (Here you have real code to handle your resource)
  • move constructor (using default constructor and swap) :

    S(S&& s) : S{} { swap(*this, s); }
    
  • assignment operator (using constructor and swap)

    S& operator=(S s) { swap(*this, s); }
    
  • destructor (deep copy of your resource)

  • friend swap (doesn't have default implementation :/ you should probably want to swap each member). This one is important contrary to the swap member method: std::swap uses move (or copy) constructor, which would lead to infinite recursion.

Related questions

0 votes
asked Jan 6, 2021 in C Plus Plus by GeorgeBell
0 votes
asked Sep 4, 2023 in Android by Robindeniel
...