将unique_ptr的向量插入另一个向量 [英] Inserting a vector of unique_ptr into another vector
问题描述
我有一个unique_ptr的向量,我想将它们附加到另一个unique_ptrs的向量。我通常会做一个简单的插入:
I have a vector of unique_ptr's and I want to append them to another vector of unique_ptrs. I would normally do a simple insert:
std::vector<std::unique_ptr<foo>> bar;
bar.push_back(std::unique_ptr<foo>(new foo(1)));
std::vector<std::unique_ptr<foo>> baz;
baz.push_back(std::unique_ptr<foo>(new foo(2)));
bar.insert(bar.end(), baz.begin(), baz.end());
但是这会给我类似的编译错误:
However this gives me compile errors similar to this:
/usr/include/c++/4.8/bits/stl_algobase.h:335: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = foo; _Dp = std::default_delete<foo>]'
*__result = *__first;
^
有一种方便的方式插入或者我必须遍历baz和push_back上吧?我目前正在使用gcc 4.8.1。
Is there a convenient way to insert or do I have to iterate over baz and push_back on bar? I'm currently using gcc 4.8.1.
感谢
推荐答案
unique_ptr
是不可分配的正常赋值运算符(错误说它被删除)。您只能移动:
unique_ptr
is not assignable with normal assignment operator (the error says it's deleted). You can only move them:
bar.insert(bar.end(),
std::make_move_iterator(baz.begin()),
std::make_move_iterator(baz.end())
);
当然,这会传输托管对象的所有权,原始指针将具有 nullptr
值。
Of course, this transfers the ownership of the managed object and original pointers will have nullptr
value.
这篇关于将unique_ptr的向量插入另一个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!