I'm trying to return a vector<unique_ptr>
from a function, but I'm running into errors. I'm using MSVC 19.33.31630.
The comments to this question recommend returning by value, but this code:
std::vector<std::unique_ptr<int>> test1()
{
std::vector<std::unique_ptr<int>> ret = { std::make_unique<int>(1) };
return ret;
}
int main()
{
std::vector<std::unique_ptr<int>> x = test1();
std::unique_ptr<int>& ptrY = x.at(0);
return 0;
}
yields this error:
Error C2280 'std::unique_ptr<int,std::default_delete<int>>::unique_ptr(const std::unique_ptr<int,std::default_delete<int>> &)': attempting to reference a deleted function
Returning by reference, as in this code:
std::vector<std::unique_ptr<int>>& test2()
{
std::vector<std::unique_ptr<int>> ret = { std::make_unique<int>(1) };
return ret;
}
int main()
{
std::vector<std::unique_ptr<int>>& y = test2();
std::cout << *(y.at(0)) << std::endl;
return 0;
}
yields the same error.
Why is this happening? Is the ownership of the unique_ptr
not transferring properly?