The code below compiles and runs just fine. Just when I thought I’m starting to get a decent grasp on rvalue reference and std::forward – this very simple code uncovers there is something very fundamental about rvalue I don’t understand. Please clarify.
#include <iostream>
#include <iomanip>
using namespace std;
void fn( int&& n )
{
cout << "n=" << n << endl;
n = 43;
cout << "n=" << n << endl;
}
int main( )
{
fn( 42 );
}
I compile it with g++ 4.7 with the following command line:
g++ –std=c++11 test.cpp
The output is:
n=42
n=43
My main issue is where does the compiler store the ‘n’ within the function fn?
I can tell some details of what happens here on the low level.
A temporary variable of type
intis created on the stack ofmain. It’s assigned with value 42.The address of the temporary is passed to
fn.fnwrites 43 by that address, changing the value of the temporary.The function exits, the temporary dies at the end of the full expression involving the call.