5

This is a simple and old question. I am sure that it must be asked somewhere else. But after over 30 minutes of googling, I decided to ask here again. The flood of information about rvalue reference makes me hard to find proper web pages for this issue.

What is the reason behind this decision that rvalues cannot bind lvalue references?

7
  • If I understood it correctly, rvalues are temporary, while lvalues still live after the expression ends. It doesn't make much sense to bind a "permanent" value to a temporary one. Commented Nov 7, 2014 at 17:59
  • @SlySherZ That is right. However, the standard says that we can bind rvalues to const lvalue references. Then the life of the rvalue is extended to the life of the const reference. Why lvalue references(without const) cannot have such behavior just like const lvalue references? Commented Nov 7, 2014 at 18:03
  • I think it has to do with compiler optimizations (rvalues are constant which allows the compiler to handle them in a more efficient way). If you want to bind and modify an rvalue efficiently, you can use move semantics (stackoverflow.com/questions/3106110/what-are-move-semantics). Commented Nov 7, 2014 at 18:10
  • @SlySherZ I am sorry but I cannot understand. Could you elaborate more? Commented Nov 7, 2014 at 18:13
  • 1
    I'm not up to date on the latest lingo about lvalues and rvalues. You can bind a const reference to a temporary object but not a non-const reference. This is just a rule, not a technical limitation. It was decided it leads to bad code. Commented Nov 7, 2014 at 18:27

1 Answer 1

7

Rvalues are usually something about to die or a literal. If this code were legal:
int &r = 5
then you would be able to modify 5, but that doesn't make sense! A reference (of any kind) is just an alias for the referenced object.
However, lvalue references to const forbid any change to the object and thus you may bind them to an rvalue.
const int &r = 5; // ok r = 10; // compilation error

Sign up to request clarification or add additional context in comments.

6 Comments

Some compilers allow int &r = 5; as an extension, so it makes sense, it's just not allowed by the standard.
Thank you. I understand your point. I thought there is some technical problem (or leads to some bad code) if we allow such rule. But still even without such things, it still seems plausible.
@NeilKirk "just"? AFAIK what the standard doesn't define is meaningless.
@Sungmin Note that you can change an rvalue through an rvalue reference.
@black The standard doesn't define Java. Is that meaningless? Is something implemented in Java but not C++ impossible because it's not in a certain document?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.