合并两个unique_ptr向量时'use of deleted function'
'use of deleted function' when merging two vectors of unique_ptr
我正在尝试合并两个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;
}
您正在尝试从常量Wrapper
对象移动。通常,移动语义还要求您要远离的对象是可变的(即不const
)。在您的代码中,add_all
方法中 other
参数的类型是 const Wrapper&
,因此other.foos
也引用常量向量,您无法离开它。
将 other
参数的类型更改为 Wrapper&
以使其正常工作。
相关文章:
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- C++ "Invalid use of 'this' in non-member function" ,
- C++14 遇到奇怪的"use of deleted function"错误
- 使用互斥锁和条件变量作为成员时如何修复"use of deleted function"?
- 构造函数导致"use of deleted function"错误
- 错误:移动承诺时"Attempt to use a deleted function"
- C++:避免"use of deleted function"错误
- C++ 11:线程创建给我一个"Attempt to use a deleted function"错误
- 如何修复库中的"invalid use of non-static member function" 导入另一个库
- C++错误:"use of deleted function" minGW_32,Qt 5.7.0,Windows 10
- C++ substr 方法 - "invalid use of ‘this’ in non-member function"
- "local variables at the outermost scope of the function may not use the same name as any parameter"是
- C++ 标准::线程"Attempt to use a deleted function"
- 合并两个unique_ptr向量时'use of deleted function'
- "invalid use of non static member function" 这是什么?
- 语义问题 "Attempt to use a deleted function" 遇到使用 std::线程用法编译 c++ 代码
- 为什么我会"use of parameter 'N' outside of function body"?
- 为什么我会收到编译错误"use of deleted function 'std::unique_ptr ..."
- 函数指针生成'invalid use of non-static member function'错误