应该复制赋值操作符杠杆std :: swap作为一般规则吗? [英] Should copy assignment operator leverage std::swap as a general rule?

查看:169
本文介绍了应该复制赋值操作符杠杆std :: swap作为一般规则吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 std :: swap 始终实现我的复制赋值运算符是一个很好的一般做法吗?我的理解是,这提供了一种方法来共享复制构造函数实现。我想避免重复实际的复制逻辑本身。所以这里是我要做的:

  class Foo 
{
public:
Foo(Foo const& other){/ *假设有效实现* /}

Foo& operator =(Foo other)
{
std :: swap(* this,other);
return * this;
}
};

将other传递给赋值运算符执行副本构造逻辑)。我假设交换将调用移动构建(这里有一个编译器生成的实现)。



我几乎每个类都实现了复制构造,因为分配&构造函数从来没有不同的实现。

解决方案

您的代码没有移动构造函数。



对于move-assign,您的运算符会自动创建一个移动构造函数,



最终结果是 ideone.com/VJKQUZ\"> = (实际代码)的无限递归调用



如果遵循0的规则,则不需要复制构造函数,移动构造函数,移动分配,复制分配或析构函数。



使用 std :: swap 如果您写了其中任何一个,可以是有用的,但是因为你必须写你的move-assign和move-construct,在 std :: swap 中是一个无限递归等待发生。 / p>

Is it a good general practice to always implement my copy assignment operators using std::swap? My understanding is that this provides a way to share the copy constructor implementation. I'd like to avoid duplicating the actual copy logic itself. So here is what I'd do:

class Foo
{
public:
    Foo(Foo const& other) { /* assume valid implementation */ }

    Foo& operator= (Foo other)
    {
        std::swap(*this, other);
        return *this;
    }
};

The act of passing "other" into the assignment operator performs copy construction (we've shared the copy logic at this point). I assume the swap will invoke move construction (which has a compiler-generated implementation here).

I've been doing this to pretty much every class I implement copy construction for, since the assignment & constructor never have different implementations.

解决方案

Your code does not have a move constructor. Your copy constructor blocks the automatic creation of a move constructor, and attempting to move your class instead copies it.

For move-assign, your operator= also blocks its automatic implementation, and can be used in its place.

The end result is an infinite recursive call of = (live code).

If you follow the rule of 0, you need neither a copy constructor, move constructor, move-assignment, copy-assignment, or destructor. If you write any of them, you should be prepared to write all of them.

Using std::swap can be useful, but because you have to write your move-assign and move-construct, doing either in terms of std::swap is an infinite recursion waiting to happen.

这篇关于应该复制赋值操作符杠杆std :: swap作为一般规则吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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