0

I have a function which creates a very large std::vector. When returning this vector, I do not want to copy it again, due to its size. Therefore, I want to return a reference to that vector. However, doing so gives me a segmentation fault. Why is this? What is the solution?

Here is my code:

std::vector<int>& Foo()
{
    std::vector<int> x(100000, 50);
    return x;
}

int main()
{
    std::vector<int> y = Foo();
    return 0;
}
Karnivaurus
  • 22,823
  • 57
  • 147
  • 247

1 Answers1

6

Your vector is a local variable. It exists within the function and is destroyed when the function ends.

Consequently, your reference is dangling. It refers to an object that no longer exists.

Just return by value; your compiler is smart enough to optimise away a pointless copy, even if you are pre-C++11 and thus don't have move semantics.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055