Search code examples
c++new-operatorvariable-assignmentplacement-new

Is such assignment a good idea in C++


A lot of classes has assignment operator (operator=) the same code as in destructor and than very similar code of copy constructor.

So is it good idea to implement the assignment in such way?

Point& operator=(const Point& point)
{
    if(&point != this)
    {
        //Call the destructor
        this->~Point();

        //Make the placement new
        //Assignment is made because some compilers optimise such code as just
        //  new Point;
        Point* p_n = new (this) Point(point);

        //We where placing in this place so pointers should be equal
        assert(p_n == this);
    }
    return *this;
}

Solution

  • Herb Sutter has addressed this in one of his GotW articles. I recommend that you read it. His conclusion:

    The original idiom is full of pitfalls, it's often wrong, and it makes life a living hell for the authors of derived classes. I'm sometimes tempted to post the above code in the office kitchen with the caption: "Here be dragons."

    From the GotW coding standards:

    • prefer writing a common private function to share code between copying and copy assignment, if necessary; never use the trick of implementing copy assignment in terms of copy construction by using an explicit destructor followed by placement new, even though this trick crops up every three months on the newsgroups (i.e., never write:

      T& T::operator=( const T& other )
      {
          if( this != &other)
          {
              this->~T();             // evil
              new (this) T( other );  // evil
          }
          return *this;
      }