std::vector<unique_ptr<int> >
将a的所有权转移到正在构造的类的正确方法是什么?
下面是我想要做什么的代码表示。我意识到这是不正确的(不会编译),并且无论我是通过值还是通过引用将向量传递给构造函数,都违反了“唯一性”。我希望Foo成为向量的新所有者,并希望调用函数放弃所有权。我需要构造函数std::unique_ptr<std::vector<std::unique_ptr<int> > >
来执行此操作吗?
oo
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::unique_ptr<T>
是不可复制但可移动的类型。在一间仅移动型std:vector<T>
化妆的std::vector<T>
举动只了。要使编译器自动移动对象,您需要具有用于移动构造或移动分配的r值。在构造函数中,对象vecOfIntPtrsOwnedByCaller
是一个l值,尽管它是一个左值,尽管其名称已经拥有指向int
s的值:当调用者创建该对象时,它们从调用者那里被“窃取”。要从l值开始移动,您需要使用std::move()
(或等效的方法):
Foo::Foo(std::vector<std::unique_ptr<int>> vecOfIntPtrsOwnedByCaller)
{
_vecOfIntPtrsOwnedByFoo = std::move(vecOfIntPtrsOwnedByCaller);
}
或者,更可取
Foo::Foo(std::vector<std::unique_ptr<int>> vecOfIntPtrsOwnedByCaller)
: _vecOfIntPtrsOwnedByFoo(std::move(vecOfIntPtrsOwnedByCaller))
{
}
后一种方法避免首先默认构造成员,然后再对其进行移动分配,而是直接移动构造成员。我想,我也将参数设为r值引用,但这不是必需的。
请注意,Foo
只能从可以绑定到r值的对象构造类型的对象,例如:
int main() {
Foo f0(std::vector<std::unique_ptr<int>>()); // OK
std::vector<std::unique_ptr<int>> v;
Foo f1(v); v// ERROR: using with an l-value
Foo f2{v}; v// ERROR: using with an l-value
Foo f3 = v; // ERROR: using with an l-value
Foo f4(std::move(v)); // OK: pretend that v is an r-value
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句