如何在 C++ 中 return 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();
}

首先,你的移动 constructor/move 赋值运算符不应该将它们的参数作为 const,这是没有意义的,当你 move,你 'steal' 的成员变量,以启用其他变量的有效构造,当您从 const 移动时,您不能这样做。

问题是您正在为结构 info 创建 copy/move 运算符,而当您使用

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));