Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::move and static_cast<T&&> different results [duplicate]

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.

like image 398
user2834162 Avatar asked Feb 15 '23 19:02

user2834162


1 Answers

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

like image 56
Kerrek SB Avatar answered Mar 03 '23 19:03

Kerrek SB