'use of deleted function' 合并 unique_ptr 的两个向量时
'use of deleted function' when merging two vectors of unique_ptr
我正在尝试合并 unique_ptr
的两个向量(即 std::move
它们从一个向量中分离出来并合并到另一个向量中)并且我将 运行 保留在 "use of deleted function..." 墙中错误文本。根据错误,我显然是在尝试使用 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;
}
您正在尝试从常量 Wrapper
对象移动。通常,移动语义还要求您要离开的对象是可变的(即不是 const
)。在你的代码中 add_all
方法中 other
参数的类型是 const Wrapper&
,因此 other.foos
也指一个常数向量,你不能离开它.
将 other
参数的类型更改为 Wrapper&
以使其工作。
我正在尝试合并 unique_ptr
的两个向量(即 std::move
它们从一个向量中分离出来并合并到另一个向量中)并且我将 运行 保留在 "use of deleted function..." 墙中错误文本。根据错误,我显然是在尝试使用 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;
}
您正在尝试从常量 Wrapper
对象移动。通常,移动语义还要求您要离开的对象是可变的(即不是 const
)。在你的代码中 add_all
方法中 other
参数的类型是 const Wrapper&
,因此 other.foos
也指一个常数向量,你不能离开它.
将 other
参数的类型更改为 Wrapper&
以使其工作。