stu_milano
stu_milano

Reputation: 81

Why is lvalue to rvalue reference binding allowed on g++ 4.4.6?

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;
}

Upvotes: 8

Views: 439

Answers (2)

Praetorian
Praetorian

Reputation: 109149

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.

Upvotes: 7

T.C.
T.C.

Reputation: 137315

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).

Upvotes: 6

Related Questions