【发布时间】:2016-08-17 22:24:23
【问题描述】:
我正在尝试合并unique_ptr 的两个向量(即std::move 它们从一个向量到另一个向量)并且我一直遇到“使用已删除函数...”的错误文本墙。根据错误,我显然正在尝试使用unique_ptr 的已删除复制构造函数,但我不确定为什么。下面是代码:
#include <vector>
#include <memory>
#include <algorithm>
#include <iterator>
struct Foo {
int f;
Foo(int f) : f(f) {}
};
struct Wrapper {
std::vector<std::unique_ptr<Foo>> foos;
void add(std::unique_ptr<Foo> foo) {
foos.push_back(std::move(foo));
}
void add_all(const Wrapper& other) {
foos.reserve(foos.size() + other.foos.size());
// This is the offending line
std::move(other.foos.begin(),
other.foos.end(),
std::back_inserter(foos));
}
};
int main() {
Wrapper w1;
Wrapper w2;
std::unique_ptr<Foo> foo1(new Foo(1));
std::unique_ptr<Foo> foo2(new Foo(2));
w1.add(std::move(foo1));
w2.add(std::move(foo2));
return 0;
}
【问题讨论】:
标签: c++ c++11 move-semantics unique-ptr deleted-functions