Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modifying the value of rvalue reference - How does it work?

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?

like image 434
Uri Avatar asked Oct 16 '12 08:10

Uri


People also ask

Can you modify an rvalue?

rvalue of User Defined Data type can be modified. But it can be modified in same expression using its own member functions only.

How do rvalue references work?

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.

What is R value Referene in C++11?

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.

How do you pass rvalue reference to a function?

If you want pass parameter as rvalue reference,use std::move() or just pass rvalue to your function.


1 Answers

I can tell some details of what happens here on the low level.

  1. A temporary variable of type int is created on the stack of main. It's assigned with value 42.

  2. The address of the temporary is passed to fn.

  3. fn writes 43 by that address, changing the value of the temporary.

  4. The function exits, the temporary dies at the end of the full expression involving the call.

like image 55
Andrey Avatar answered Oct 15 '22 09:10

Andrey