Foo类具有一个右值引用构造函数,该右值引用构造函数可移动unique_ptr
的包含向量,因此以下代码为什么在std::move
的Foo()
上带有或不带有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; }
Foo类具有一个右值引用构造函数,该构造函数可移动包含的unique_ptrs向量,因此以下代码为何在Foo()上带有或不带有std :: move的情况下都给出以下错误,无论为什么[
f = std::move(Foo());
不调用move构造函数。它调用移动分配运算符。此外,它是多余的,因为Foo()
已经是一个右值,所以等效于:
f = Foo();
由于您已声明移动构造函数,因此未声明移动分配运算符-因此没有一个。所以您要么必须提供一个:
Foo& operator=(Foo&& other) {
m_bar = std::move(other.m_bar);
return *this;
}
或者,由于所有成员都自己实现了移动操作,因此您可以删除移动构造函数,并依靠编译器生成的隐式移动构造函数和移动赋值。