Is such assignment a good idea in C++

Deadly 提交于 2019-12-06 01:21:41
Fred Larson

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

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.

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