views:

206

answers:

4

Hi,

Can anybody explain to me why there is a difference between these two statements?

class A{};

const A& a = A();         // correct 

A& b = A();               // wrong

It says invalid initialization of non-const reference of type A& from a temporary of type A

Why does const matter here?

+1  A: 

For a temporary/rvalue, you can only have a const reference.

You can have a non-const reference to a non-temporary/lvalue.

A a;
A& b = a;

I believe the reason why is to reinforce the fact that a rvalue is temporary as there is little value in being able to modify something that is going to disappear momentarily.

R Samuel Klatchko
Granted; I think the OP is looking for why that is the case.
fbrereto
+1  A: 

In C++ language it is illegal to attach a non-const reference to an rvalue, while it is perfectly OK to attach a const reference to an rvalue. For example, this is legal

const int& r = 5;

while this is not

int &r = 5; // ERROR

A temporary object of type A returned by the expression A() is an rvalue, so the above rule applies in your case as well.

AndreyT
An rvalue is an unnamed temporary value, like the return value of a function.
thebretness
@thebretness: Not necessarily. For example, a enum constant is an rvalue, yet it is *named*.
AndreyT
+12  A: 

Non-const references must be initialised with l-values. If you could initialise them with temporaries, then what would the following do?

int& foo = 5;
foo = 6; // ?!

const references have the special property that they extend the life of the referee, and since they are const, there is no possibility that you'll try to modify something that doesn't sit in memory. For example:

const int& foo = 5;
foo = 6; // not allowed, because foo is const.

Remember that references actually have to refer to something, not just temporary variables. For example, the following is valid:

int foo = 5;
int& bar = foo;
bar = 6;
assert(foo == 6);
Peter Alexander
Wait, so does that mean I can use `const classA`? I thought the temp would die on the next line.
Lucas
Yes, you could use that. The temporary will last for as long as the reference variable does: http://herbsutter.spaces.live.com/blog/cns!2D4327CC297151BB!378.entry
Josh Townzen
Awesome, thanks. On SO, you learn something new every day...
Lucas
Yeah, const references extend the life of the temporary to the life of the references. In many ways, you can think of `const T)
Peter Alexander
+3  A: 

The terminology on this is a little confusing; you may want to research them a bit further. Here's the short answer though:

You are assigning a temporary object (the result of calling the class's constructor) to a variable. A temporary object is an R-value. You can't assign an R-value to a non-const reference.

You are allowed to assign an R-value to a const reference, although the rationale for allowing it is pretty obscure.

jwismar