4

Oh, I found one problem in my rvalue-references comprehension. The problem:

int&& foo()
{
    int n = 5;
    return std::move(n);
}

int bar()
{
    int y = 10;
    return y;
}

int main()
{
    int&& p = foo();
    bar();
    std::cout << p;
}

The compiler doesn't write error or warning that we return local address from function foo. And I'm going to replace value 5 by 10 in function bar. But result is 5. If I change std::move to static_cast compiler gives error and result is 10. Why is it going so? I use gcc 4.8.1.

tshepang
  • 12,111
  • 21
  • 91
  • 136
user2834162
  • 139
  • 2
  • 3
    The question is slightly different, but the answer is the same as [Is returning by rvalue reference more efficient?](http://stackoverflow.com/questions/1116641/is-returning-by-rvalue-reference-more-efficient) – Zac Howland Oct 30 '13 at 20:22
  • you seem to be using rvalue refereces as they were some kind of magic thing. they are not. they are references. don't return references to function local things. they will dangle. also, avoid unnecessary `std::move` calls. If you return a function local thing, you don't need `std::move`. In fact, using `std::move` in this case potentially harms performance since it effectivly disables the return value optimization. – sellibitze Nov 04 '13 at 13:36

1 Answers1

8

Returning a reference to a local variable is undefined behaviour. Anything could happen. Don't do it.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084