I have a simple function which should construct a few objects and return a vector of them while also transferring the ownership. I thought the best way of doing this is simply returning a std::vector<std::unique_ptr<int>>
of the objects (let's say they are int
).
When I tried the following function:
std::vector<std::unique_ptr<int>> create_stuff() {
auto first = std::make_unique<int>(1);
auto second = std::make_unique<int>(2);
return {std::move(first), std::move(second)};
}
I was welcomed with a very very long compile error ending with:
xmemory0(737): error C2280: 'std::unique_ptr<int,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)':
attempting to reference a deleted function
I thought the problem was with the function itself, however the following solution worked fine:
std::vector<std::unique_ptr<int>> create_stuff() {
auto first = std::make_unique<int>(1);
auto second = std::make_unique<int>(2);
std::vector<std::unique_ptr<int>> results;
results.push_back(std::move(first));
results.push_back(std::move(second));
return results;
}
Why does the second solution work but not the first one? Is there a workaround that would allow me to use the short and simple syntax with the initializer list?