如何在c++中返回unique_ptr的列表
How to return a list of unique_ptr in c++?
这里有一个代码片段,我想从函数中获得unique_ptr的列表。尽管我已经向这个结构添加了Copy/move构造函数,但vs编译器仍然报告了一个c2280错误(试图引用一个已删除的函数(。有人知道发生了什么吗>?
#include<iostream>
#include<memory>
#include <list>
using namespace std;
struct info {
info() {
cout << "c" << endl;
}
~info() {}
info(const info&w) {
cout << "cc" << endl;
}
info(const info&&w) {
cout << "ccc" << endl;
}
info& operator==(const info&) {
cout << "=" << endl;
}
info& operator==(const info&&) {
cout << "==" << endl;
}
};
typedef unique_ptr<info> infop;
list<infop> test() {
list<infop> infopList;
info t,t1;
infop w = make_unique<info>(t);
infop w1 = make_unique<info>(t1);
infopList.push_back(w);
infopList.push_back(w1);
return infopList;
}
void main() {
list<infop> pl = test();
}
首先,您的move构造函数/move赋值运算符不应该将其参数作为const,这是没有意义的,当您move
时,您"窃取"了变量的成员,以实现其他变量的有效构造,当您从const移动时,您不能这样做。
问题是,您正在为结构info
创建复制/移动运算符,并且当您使用时
infopList.push_back(w);
infopList.push_back(w1);
您正在尝试复制unique_ptr<info>
,unique_ptr
没有复制构造函数,只有移动构造函数,您需要移动变量。
infopList.push_back(std::move(w));
infopList.push_back(std::move(w1));
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有为自己的结构调用列表推回方法
- 使用简单类型列表实现的指数编译时间.为什么
- 一对向量构造函数:初始值设定项列表与显式构造
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 通过for循环使用用户输入填充列表
- C++:如何使函数只返回作为列表一部分的字符串
- 概念中的cv限定符需要表达式参数列表
- 下面是我为检测链接列表中的循环而制作的代码
- 建议在运行时将带有类实例的列表从c++导入qml
- 如何维护资源管理器项目视图中当前可见的项目列表
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在卡萨布兰卡形成编码参数的列表