c++ - 根据 move 构造函数实现复制赋值运算符

标签 c++ c++11 move-semantics

考虑以下概念/示例类

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 指出异常安全和自赋值问题是通过这种方式解决的)。

在实现 move 构造函数和 move 赋值运算符时,我发现存在一些“代码重复”,我通过添加 MoveImpl(&&) 私有(private)方法“消除”了这些代码。

我的问题是,既然我们知道复制赋值运算符会获取对象的新拷贝,该拷贝将在作用域结束时被清理,那么使用 MoveImpl() 是否正确/良好做法> 实现复制赋值运算符功能的函数。

最佳答案

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

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

关于c++ - 根据 move 构造函数实现复制赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39386209/

相关文章:

c++ - protobuf "oneof"子 protobuf 对象指针杀死程序

c++ - constexpr 适用于 Ubuntu,但不适用于 MacOS

c++ - 使用 try/catch 处理字符串流错误

c++ - 为 std::vector<std::vector<TYPE>> 中的内部 vector 保留内存

rust - 如何在具有可变字段的结构上实现 move 语义?

c++ - 为什么在动态数组中自动解除对 char 指针的引用

c++ - 参数列表中的元组

c++ - C++中的年持续时间算法

c++ - 当源 obj 被销毁时,使用 move cstor 是否会丢失内存?

c++ - std::move 是否应该用于 return-statements 以提高效率?