Can I use placement new(this) in operator=?

后端 未结 2 1431
遇见更好的自我
遇见更好的自我 2020-12-11 03:14

Background: I have a complicated class with many variables. I have a sound and tested copy constructor:

Applepie::Applepie( const Applepie          


        
2条回答
  •  独厮守ぢ
    2020-12-11 03:46

    As Herb Sutter in "Exceptional C++" states, it is not exception safe. That means, if anything is going wrong during new or construction of the new object, the left hand operand of the assignment is in bad (undefined) state, calling for more trouble. I would strongly recommend using the copy & swap idiom.

    Applepie& Applepie::operator=(Applepie copy)
    {
      swap(m_crust, copy.m_crust);
      swap(m_filling, copy.m_filling);
      return *this;
    }
    

    When your object uses the Pimpl idiom (pointer to implementation) also, the swap is done by changing only two pointers.

提交回复
热议问题