根据移动构造函数实现复制赋值运算符

Implementing copy assignment operator in terms of move constructor

考虑以下 concept/example class

class Test
{
public:
    explicit Test(std::string arg_string)
        : my_string( std::move(arg_string) )
    { }

    Test(const Test& Copy) {
        this->my_string = Copy.my_string;
    }

    Test& operator=(Test Copy) {
        MoveImpl( std::move(Copy) );
        return *this;
    }

    Test(Test&& Moved) {
        MoveImpl( std::forward<Test&&>(Moved) );
    }

    Test& operator=(Test&& Moved) {
        MoveImpl( std::forward<Test&&>(Moved) );
        return *this;
    }

private:
    void MoveImpl(Test&& MoveObj) {
        this->my_string = std::move(MoveObj.my_string);
    }

    std::string my_string;
};

复制构造函数像往常一样接受一个const&

复制赋值运算符是根据复制构造函数实现的(如果我没记错的话,Scott Meyers 指出异常安全和自赋值问题是通过这种方式解决的)。

在实现移动构造函数和移动赋值运算符时,我发现有一些 "code duplication",我通过添加 MoveImpl(&&) 私有方法"eliminated"。

我的问题是,既然我们知道复制赋值运算符会获取对象的新副本,该副本将在作用域结束时被清理,那么 correct/good 实践是否使用 MoveImpl()函数来实现复制赋值运算符的功能。

你的思路是对的,但是共同点在交换操作上。

如果你尝试早点这样做,你就失去了在构造函数的初始化列表中初始化成员的机会,这在概念上会导致成员的冗余默认初始化和整齐地处理异常的困难。

这更接近您想要的模型:

class Test
{
public:
    explicit Test(std::string arg_string)
    : my_string( std::move(arg_string) )
    { }

    Test(const Test& Copy) : my_string(Copy.my_string)
    {
    }

    Test& operator=(Test const& Copy)
    {
        auto tmp(Copy);
        swap(tmp);
        return *this;
    }

    Test(Test&& Moved) : my_string(std::move(Moved.my_string))
    {
    }

    Test& operator=(Test&& Moved)
    {
        auto tmp = std::move(Moved);
        swap(tmp);
        return *this;
    }

    void swap(Test& other) noexcept
    {
        using std::swap;
        swap(my_string, other.my_string);
    }

private:

    std::string my_string;
};

当然,在现实中,零规则应该始终优先,除非你绝对需要在析构函数中进行特殊处理(你几乎从不这样做):

class Test
{
public:
    explicit Test(std::string arg_string)
    : my_string( std::move(arg_string) )
    { }

// copy, assignment, move and move-assign are auto-generated
// as is destructor

private:

    std::string my_string;
};

复制赋值运算符的按值签名的美妙之处在于它消除了对移动赋值运算符的需要(前提是您正确定义了移动构造函数!)。

class Test
{
public:
    explicit Test(std::string arg_string)
        : my_string( std::move(arg_string) )
    { }

    Test(const Test& Copy)
        : my_string(Copy.my_string)
    { }

    Test(Test&& Moved)
        : my_string( std::move(Moved.my_string) )
    { }

    // other will be initialized using the move constructor if the actual
    // argument in the assignment statement is an rvalue
    Test& operator=(Test other)
    {
        swap(other);
        return *this;
    }

    void swap(Test& other)
    {
        std::swap(my_string, other.my_string);
    }

private:
    std::string my_string;
};