如何将一个 std::vector<unique_ptr<int> >
的所有权转移给正在构建的类?以下是我想要做的代码表示。我意识到它不正确(无法编译),无论我是按值传递还是引用传递向构造函数传递向量都违反了“唯一性”。我希望Foo成为向量的新所有者,并希望调用函数放弃所有权。我需要构造函数采用 std::unique_ptr<std::vector<std::unique_ptr<int> > >
实现吗?
Foo.h
class Foo
{
public:
Foo(vector<std::unique_ptr<int> > vecOfIntPtrsOwnedByCaller);
private:
vector<std::unique_ptr<int> > _vecOfIntPtrsOwnedByFoo;
}
Foo.cpp
Foo::Foo(std::vector<std::unique_ptr< int> > vecOfIntPtrsOwnedByCaller)
{
_vecOfIntPtrsOwnedByFoo = vecOfIntPtrsOwnedByCaller;
}
希望能得到任何帮助 - 我搜索了整个网络以寻找正确的方法来完成这件事。谢谢!
std::vector<std::unique_ptr<int>>
需要使用临时变量或者调用者自己使用std::move
来移动它们的向量,因为它不能被简单地复制。如果您想使其更加明确,请考虑使用std::vector<...>&&
。之后,在成员初始化器中使用std::move
进行移动。 - Xeo