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?
rvalue of User Defined Data type can be modified. But it can be modified in same expression using its own member functions only.
An rvalue reference is formed by placing an && after some type. An rvalue reference behaves just like an lvalue reference except that it can bind to a temporary (an rvalue), whereas you can not bind a (non const) lvalue reference to an rvalue.
In C++11, however, the rvalue reference lets us bind a mutable reference to an rvalue, but not an lvalue. In other words, rvalue references are perfect for detecting whether a value is a temporary object or not.
If you want pass parameter as rvalue reference,use std::move() or just pass rvalue to your function.
I can tell some details of what happens here on the low level.
A temporary variable of type int
is created on the stack of
main
. It's assigned with value 42.
The address of the temporary is passed to fn
.
fn
writes 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With