#include <memory>
class A
{
public:
A()
{
}
A( const A&& rhs )
{
a = std::move( rhs.a );
}
private:
std::unique_ptr<int> a;
};
此代码无法使用 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 );
^
我知道 unique_ptr 的复制构造函数和复制赋值构造函数已删除且无法调用,但我认为通过使用 std::move
在这里我会调用 move 赋值构造函数。 The official documentation甚至显示正在完成这种类型的任务。
我没有看到我的代码中有什么错误?
最佳答案
A( const A&& rhs )
// ^^^^^
删除const
——从一个对象 move 是破坏性的,所以你不能从一个const
对象 move 是公平的。
关于c++ - "error: use of deleted function"在 move 构造函数中对 unique_ptr 调用 std::move 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42621665/