2

If I have a function that returns some object like

std::vector<int> foo()
{
    std::vector<int> v;
    v.push_back(1);
    return v;
}

then what's the difference between saying

std::vector<int> &&v = foo();

and

std::vector<int> v = foo();

?

(Why) would I prefer either over the other?

(I suspect this might be a duplicate question, but I couldn't find the right search terms.)

user541686
  • 205,094
  • 128
  • 528
  • 886
  • does this one help? http://stackoverflow.com/questions/13618506/is-it-possible-to-stdmove-objects-out-of-functions-c11/13618587#13618587 – billz Jul 21 '13 at 04:03
  • @billz: Yeah, it basically seems to say that they do the same thing when you're returning an object. – user541686 Jul 21 '13 at 04:30

1 Answers1

3

Reading one of these (and thus knowing that it's doing something reasonable) requires understanding about temporaries and how binding a temporary to a reference extends the lifetime of the temporary. The other is:

std::vector<int> v = foo();

Always pick the one that's easier to understand. It also works just as well if foo returned a const& or a &&, whereas storing it by && would only work if it returns by value or by &&.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982