且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

这样的分配在C ++中是一个好主意吗

更新时间:2023-11-28 08:48:52

草药萨特他的GotW文章之一.我建议您阅读它.他的结论:

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."

根据GotW编码标准:

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