1

Here is a code snippet which i want to get a list of unique_ptr from a function. Although i have added Copy/move Constructor to this struct,the vs compiler still has reported a c2280 error(attempting to reference a deleted function) .Does anybody know what's going on>?

#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();
}
Y.Lex
  • 241
  • 1
  • 7
  • 1
    If the pointer is unique, you can't copy it into something else. A shared pointer would be ok. You might get away with `emplace_back`, but I suspect you may run into trouble later when you try to use what's in your vector. – doctorlove Jul 30 '18 at 08:16
  • The 2 move methods should not take `const` parameters. – Richard Critten Jul 30 '18 at 08:16

1 Answers1

1

First of all, your move constructor/move assignment operator shouldn't take their parameters as const, which makes no sense, when you move, you 'steal' the members of the variable, to enable a efficient construction of other variable, when you move from const, you can not do that.

The problem is that you're making copy/move operators for your struct info, and when you're using

infopList.push_back(w);
infopList.push_back(w1);

You're trying to make a copy of a unique_ptr<info>, unique_ptr does not have a copy constructor, only a move constructor, you need to move your variables.

infopList.push_back(std::move(w));
infopList.push_back(std::move(w1));
Kaldrr
  • 2,780
  • 8
  • 11