What is the Rule of Four (and a half)?

后端 未结 2 549
离开以前
离开以前 2020-12-29 07:52

For properly handling object copying, the rule of thumb is the Rule of Three. With C++11, move semantics are a thing, so instead it\'s the Rule of Five. However, in discussi

2条回答
  •  轮回少年
    2020-12-29 08:37

    So what exactly is the Rule of Four (and a half)?

    “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.

    Which function is the half?

    From previous article:

    "To implement the Copy-Swap idiom your resource management class must also implement a swap() function to perform a member-by-member swap (there’s your “…(and a half)”)"

    so the swap method.

    Are there any disadvantages or warnings for this approach, compared to the Rule of Five?

    The warning I already wrote is about to write the correct swap to avoid the infinite recursion.

提交回复
热议问题