移动包含向量<unique_ptr<T>>的可分配类 [英] Move assignable class containing vector<unique_ptr<T>>
问题描述
类 Foo 有一个右值引用构造函数,用于移动 unique_ptr
的包含向量,那么为什么以下代码会给出以下错误,无论是否带有 std::move
在 main
中的 Foo()
上?
The class Foo has an rvalue reference constructor that moves the contained vector of unique_ptr
s so why does the following code give the following error, both with or without the std::move
on the Foo()
in main
?
error C2280: 'std::unique_ptr<SomeThing,std::default_delete<_Ty>> &std::unique_ptr<_Ty,std::default_delete<_Ty>>::operator =(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
class Foo{
public:
Foo(){
}
Foo(Foo&& other) :
m_bar(std::move(other.m_bar))
{};
std::vector<std::unique_ptr<SomeThing>> m_bar;
};
int main(int argc, char* argv[])
{
Foo f;
f = std::move(Foo());
return 0;
}
推荐答案
这个:
f = std::move(Foo());
不调用移动构造函数.它调用移动赋值运算符.此外,它是多余的,因为 Foo()
已经是一个右值,所以等价于:
doesn't call the move constructor. It calls the move assignment operator. Furthermore, it's redundant, since Foo()
is already an rvalue so that's equivalent to:
f = Foo();
因为您声明了一个移动构造函数,所以没有声明移动赋值运算符——所以没有.所以你要么必须提供一个:
Since you declared a move constructor, the move assignment operator isn't declared - so there isn't one. So you either have to provide one:
Foo& operator=(Foo&& other) {
m_bar = std::move(other.m_bar);
return *this;
}
或者,由于您的所有成员都自己实现移动操作,您可以删除移动构造函数并依赖编译器生成的隐式移动构造函数和移动赋值.
Or, since all your members implement move operations themselves, you could just delete your move constructor and rely on the compiler-generated implicit move constructor and move assignment.
这篇关于移动包含向量<unique_ptr<T>>的可分配类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!