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

后端 未结 2 1430
遇见更好的自我
遇见更好的自我 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.

    0 讨论(0)
  • 2020-12-11 04:03

    In addition to Rene's answer, there is also the problem of what would happen if ApplePie was a base class of the actual object: ApplePie would be replacing the object with an object of the wrong type!

    0 讨论(0)
提交回复
热议问题