[英]“Use of deleted function” when calling `std::unique_ptr` move constructor?
[英]“error: use of deleted function” when calling std::move on unique_ptr in move constructor
#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
,我将改为调用移动分配构造函数。 官方文档甚至显示了这种分配类型。
我没有看到的代码有什么问题?
A( const A&& rhs )
// ^^^^^
删除const
从对象移出是破坏性的,因此不能从const
对象移出是很公平的。
当我没有明确声明移动构造函数和复制构造函数时,我也遇到了这个错误。
我使用了https://en.cppreference.com/w/cpp/language/move_assignment中的示例,但是当我尝试实现移动分配运算符时
A& operator=(A&& other){...}
没有实现两个核心
A(const A& o) : s(os) { ... } A(A&& o) : s(std::move(os)) { }
尝试使用移动分配时,对std :: move的调用未编译,并且出现了此确切错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.