"错误:使用已删除的函数"在移动构造函数中调用unique_ptr上的std :: move时

Fat*_*unk 9 c++ move c++11

#include <memory>

class A
{
public:
    A()
    {
    }

    A( const A&& rhs )
    {
        a = std::move( rhs.a );
    }

private:
    std::unique_ptr<int> a;
};
Run Code Online (Sandbox Code Playgroud)

此代码将无法使用g ++ 4.8.4进行编译,并引发以下错误:

error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>
::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_de
lete<int>]’
     a = std::move( rhs.a );
       ^
Run Code Online (Sandbox Code Playgroud)

据我所知,unique_ptr的复制构造函数和复制赋值构造函数已被删除,无法调用,但我想std::move在这里使用我会调用移动赋值构造函数.官方文档甚至显示了这种类型的任务正在完成.

我的代码中有什么问题我没看到?

Que*_*tin 21

A( const A&& rhs )
// ^^^^^
Run Code Online (Sandbox Code Playgroud)

放弃const- 从一个物体移动是破坏性的,所以你不能从一个const物体移动是公平的.

  • 作为一个样式点,更喜欢使用初始化程序:`A(A && rhs):a(std :: move(rhs.a)){}` (2认同)