这样的分配在C ++中是一个好主意吗 [英] Is such assignment a good idea in C++

查看:98
本文介绍了这样的分配在C ++中是一个好主意吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多类的赋值运算符(operator =)与析构函数中的代码相同,而与复制构造函数的代码非常相似.

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

推荐答案

草药萨特他的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;
}

这篇关于这样的分配在C ++中是一个好主意吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆