c++ - 如何在 C++ 中返回 unique_ptr 列表?

标签 c++ c++14 smart-pointers

<分区>

这是我想从函数中获取 unique_ptr 列表的代码片段。尽管我已经向这个结构添加了复制/移动构造函数,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 时,这是没有意义的。 ,您“窃取”了变量的成员,以启用其他变量的有效构造,当您从 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));

关于c++ - 如何在 C++ 中返回 unique_ptr 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51589631/

相关文章:

c++ - 对用于 cuda 实现的函数的 undefined reference

c++ - 按名称调用不同签名的方法

c++11 - C++中std::shared_ptr的克隆模式

c++ - 存储指向自身的弱指针

c++ - 使用 boost 转换度分秒弧度 boost_1_48_0

c++ - 基于类型创建具有默认参数的模板

c++ - 通过引用传递指向二维数组的指针

c++ - 枚举(类)允许的类型是什么?

c++ - 对象、右值引用、常量引用之间的重载解析

c++ - 模板类的智能指针?