I'm learning rvalue feature of C++11. C++ Primer 5th edition says that an rvalue reference can only bind to an rvalue, but when I tried to compile this program, it passed, and the output is 1 1
.
I don't understand why. I'm using g++ 4.4.6, and compiled it with
g++ -Wall -std=c++0x test.cpp -o test
#include <iostream>
using namespace std;
int main()
{
int i = 0;
int &&rr = i;
rr = 1;
std::cout << rr << std::endl;
std::cout << i << std::endl;
return 0;
}
An lvalue reference can bind to an lvalue, but not to an rvalue.
“l-value” refers to a memory location that identifies an object. “r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable.
Rvalue references enable you to write one version of a function that accepts arbitrary arguments. Then that function can forward them to another function as if the other function had been called directly. Consider the following example that declares four types, W , X , Y , and Z .
An rvalue (so-called, historically, because rvalues could appear on the right-hand side of an assignment expression) is an xvalue, a temporary object or subobject thereof, or a value that is not associated with an object. A prvalue (“pure” rvalue) is an rvalue that is not an xvalue.
Your code is invalid, an lvalue cannot bind to an rvalue reference just as the book says. g++5.1 rejects your code with the error message
main.cpp:8:16: error: cannot bind 'int' lvalue to 'int&&' int &&rr = i; ^
g++4.4.6 was released in April, 2011, less than a month after the final draft for C++11 was approved. The behavior you're seeing is either a gcc bug, or the behavior specified by some early working draft of the C++11 standard.
The current rule is described in N2844 and implemented in gcc 4.5.
The GCC 4.4 series was first released in April 2009, and the trunk was closed to all but regression and documentation fixes well before that, in November 2008.
The rule that prevents rvalue references from binding to lvalues was voted into the standard in March 2009, as the paper N2844, after being first suggested in December 2008, in the paper N2812.
Thus, the new rule couldn't possibly be implemented in time for GCC 4.4 (it was in fact implemented for GCC 4.5).
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