C++ 合并两个唯一ptr向量时“使用已删除函数”
我试图合并两个唯一的向量,即std::将它们从一个向量移到另一个向量中,我一直在使用deleted函数。。。错误文本墙。根据错误,我显然试图使用unique_ptr的deleted copy构造函数,但我不知道为什么。代码如下:C++ 合并两个唯一ptr向量时“使用已删除函数”,c++,c++11,move-semantics,unique-ptr,deleted-functions,C++,C++11,Move Semantics,Unique Ptr,Deleted Functions,我试图合并两个唯一的向量,即std::将它们从一个向量移到另一个向量中,我一直在使用deleted函数。。。错误文本墙。根据错误,我显然试图使用unique_ptr的deleted copy构造函数,但我不知道为什么。代码如下: #include <vector> #include <memory> #include <algorithm> #include <iterator> struct Foo { int f; Foo(
#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;
}
您正在尝试从常量包装器对象移动。通常,移动语义还要求要移动的对象是可变的,即不是常量。在代码中,add_all方法中的另一个参数的类型是const Wrapper&,因此other.foos也引用一个常量向量,您不能离开它
将其他参数的类型更改为Wrapper&以使其正常工作。谢谢!这似乎已经做到了!我认为移动语义的可变性是有意义的,因为其他的向量将因此而变得无效。@AUD_for_IUV欢迎使用堆栈溢出!:-