0
votes

I cannot move a std::vector<std::unique_ptr<..>> from a function: MSVC complains (C2280) about attempting to reference a deleted function.

How would this work?

#include <vector>
#include <iostream>
#include <memory>

using namespace std;

class foo {
public:
   int i;
};

vector<unique_ptr<foo>> test() {
   vector<unique_ptr<foo>> ret{};

   auto f = make_unique<foo>();
   f->i = 1;
   ret.push_back(move(f));

   return move(ret);
}

int main(int argc, char** argv) {
   auto t = test();
   for (auto j : t) {
// fails here: --^
      cout << j->i << endl;
   }

   getchar();
}

The complete error message reads:

'std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function

1
The error message points to the foreach loop.tkausl
sorry, on my waysanta
return move(ret); just return ret; is enough.hellow
You do know how a range-based for loop is working? What you're attempting to do is copying the values from the vector.Some programmer dude
I tried to move(ret) because I thought that the copying might happen there.santa

1 Answers

6
votes

It's not the function, it's the loop...

for (auto j : t)

... which attempts to copy-initialize j for each element of t in turn. Recall that a plain auto means value semantics. Use a reference instead:

for (auto const& j : t)