Reputation: 1003
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
Upvotes: 0
Views: 229
Reputation: 170045
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)
Upvotes: 6