jeudi 20 octobre 2022

Returning std::vector<:unique_ptr>> from function

I'm trying to return a vector of unique_ptrs from a function, but I'm running into errors (MSVC 19.33.31630).

The comments to this question recommend returning by value, but

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 the error Error C2280 'std::unique_ptr<int,std::default_delete>::unique_ptr(const std::unique_ptr<int,std::default_delete> &)': attempting to reference a deleted function

Returning by reference, as in

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? Any help would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire