Is such assignment a good idea in C++

若如初见. 提交于 2020-01-02 07:14:14

问题


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;
}

回答1:


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;
    }
    



回答2:


No. This is a bad idea, even though the C++ Standard uses this kind of thing as an example in a discussion of object lifetime. For a value type like Point it's not so bad, but if you derive from this class, this assignment implementation will change the type of the object from your derived type to Point; if there are virtual functions involved, you'll see a dramatic change in behavior.



来源:https://stackoverflow.com/questions/15932333/is-such-assignment-a-good-idea-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!