0

I'm trying to set a function that returns a vector of unique_ptrs, but I'm failing to do so. A simplified version of what I produced is the following:

#include <memory>
#include <vector>

std::vector<std::unique_ptr<int>>&& Foo()
{
    std::vector<std::unique_ptr<int>> v;
    v.emplace_back(std::make_unique<int>(1));
    v.emplace_back(std::make_unique<int>(2));
    v.emplace_back(std::make_unique<int>(3));
    return std::move(v);
}

int main()
{
    auto bar = Foo();
    return 0;
}

However I'm getting a segmentation fault, once the value I return from the function Foo is assigned to the bar variable. What is the problem here?

Mdp11
  • 552
  • 4
  • 13
  • 1
    You are returning an rvalue reference to an object (`v`) that is going out of scope. Why don't you return the object itself as `std::vector>`? – Werner Henze Mar 13 '21 at 19:52
  • 1
    You return a dangling reference to a local variable. You should return by value and not bother explicitly moving as the compiler will do that implicitly. – underscore_d Mar 13 '21 at 19:52
  • Thanks, that was the problem. It just seems a bit odd to not using move semantics when dealing with unique_ptr – Mdp11 Mar 13 '21 at 19:54
  • you **can** use move semantics, but not like this. (a) return by value. (b) the compiler will implicitly move the local variable into the result, so don't explicitly do it. – underscore_d Mar 13 '21 at 19:55

0 Answers0