100

Wrong form:

int &z = 12;

Correct form:

int y;
int &r = y;

Question:
Why is the first code wrong? What is the "meaning" of the error in the title?

4
  • 5
    Temporaries cannot be bound to non-constant references. int(12) is a temporary in this case. Commented Nov 28, 2011 at 9:01
  • 3
    Note that there isn't a strict technical reason for this restriction. It would have been just as easy to implement to allow mutable references to temporaries. Forbidding it is a design decision of C++, since such a construction would be poor design with far greater risk of being inadvertently abused than genuine utility. (I only once found a contrived need for such a thing.)
    – Kerrek SB
    Commented Nov 28, 2011 at 12:50
  • @KerrekSB the most common need for a binding ref to rvalue object probably is (ostringstream() << "x=" << x).str()
    – curiousguy
    Commented Nov 29, 2011 at 3:51
  • @curiousguy: Yes, that's the content of the link I posted.
    – Kerrek SB
    Commented Nov 29, 2011 at 4:03

5 Answers 5

140

C++03 3.10/1 says: "Every expression is either an lvalue or an rvalue." It's important to remember that lvalueness versus rvalueness is a property of expressions, not of objects.

Lvalues name objects that persist beyond a single expression. For example, obj , *ptr , ptr[index] , and ++x are all lvalues.

Rvalues are temporaries that evaporate at the end of the full-expression in which they live ("at the semicolon"). For example, 1729 , x + y , std::string("meow") , and x++ are all rvalues.

The address-of operator requires that its "operand shall be an lvalue". if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue.

 &obj; //  valid
 &12;  //invalid
15
  • 2
    "if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue." if only C++ was that simple! (but the nuance is not really relevant here) "Rvalues are temporaries" temporary what? objects?
    – curiousguy
    Commented Nov 28, 2011 at 10:42
  • 2
    @curiousguyRvalues are temporaries that disappear at the end of the full-expression in which they live. To simply answer why the express int & = 12; is invalid, the standard says a string literal is an lvalue, other literals are rvalues.
    – BruceAdi
    Commented Nov 28, 2011 at 11:41
  • @curiousguy: Yes. Rvalues are temporary objects, but not all rvalues are temporary object; some are not even objects. Commented Nov 28, 2011 at 14:17
  • "For example, 1729 , x + y , std::string("meow") , and x++ are all rvalues." but std::string("meow") constructs an object of type std::string and yields a rvalue that designates this object, 1729 has no side-effect and yields value 1729 as an rvalue of type int.
    – curiousguy
    Commented Nov 29, 2011 at 2:42
  • 1
    @curiousguy: The statement "Lvalues name objects that persist beyond a single expression." is a 100% correct statement. On the contrary, your example (const int &)1 is incorrect, because It is NOT a "named" object. Commented Nov 29, 2011 at 12:19
57
int &z = 12;

On the right hand side, a temporary object of type int is created from the integral literal 12, but the temporary cannot be bound to non-const reference. Hence the error. It is same as:

int &z = int(12); //still same error

Why a temporary gets created? Because a reference has to refer to an object in the memory, and for an object to exist, it has to be created first. Since the object is unnamed, it is a temporary object. It has no name. From this explanation, it became pretty much clear why the second case is fine.

A temporary object can be bound to const reference, which means, you can do this:

const int &z = 12; //ok

C++11 and Rvalue Reference:

For the sake of the completeness, I would like to add that C++11 has introduced rvalue-reference, which can bind to temporary object. So in C++11, you can write this:

int && z = 12; //C+11 only 

Note that there is && intead of &. Also note that const is not needed anymore, even though the object which z binds to is a temporary object created out of integral-literal 12.

Since C++11 has introduced rvalue-reference, int& is now henceforth called lvalue-reference.

0
10

12 is a compile-time constant which can not be changed unlike the data referenced by int&. What you can do is

const int& z = 12;
26
  • 2
    @curiousguy, be consistent, you've said "You have to understand that these are C++ rules. They exist, and don't need any justification" (not to mention the first edition). How am I to interpret your complaining of not giving what is according to yourself is not needed? Commented Nov 28, 2011 at 11:21
  • 2
    @MichaelKrelin-hacker: Technically not, you cannot (ever) bind a reference to a value (or compile time constant), the standard is quite explicit as to what actually happens: Otherwise, a temporary of type “cv1 T1” is created and initialized from the initializer expression using the rules for a non-reference copy-initialization (8.5). The reference is then bound to the temporary That is, the syntax is allowed, but the semantics are not those of binding a reference to the constant, but rather binding it to the temporary that is implictly created. Commented Nov 28, 2011 at 13:01
  • 1
    @curiousguy: The rules of the language are part of the design, and more often than not, there are justifications as to why the language was designed like so. In this particular case, as in C you are not allowed to take the address of an value (it does not have one), nor can you bind a reference. Now consider a function void f( vector<int> const & ), which is idiomatic to pass a vector that is not to be modified. The problem now is that f( vector<int>(5) ) would be incorrect, and the user would have to provide a different overload void f( vector<int> v ) { f(v); } which is trivial. Commented Nov 28, 2011 at 13:20
  • 1
    ... now because that would be painful to the users of the language, the designers decided that the compiler would perform the equivalent operation for you, in the call f( vector<int>(5) ), the compiler creates a temporary and then binds the reference to that temporary, and similarly if there was an implicit conversion from 5 directly. This allows the compiler to generate a single signature for the function and enables a single user implementation of the function. From there on, similar behaviour is defined for the rest of the uses of constant references for consistency. Commented Nov 28, 2011 at 13:23
  • 1
    @MichaelKrelin-hacker: references are aliases to objects, and a value is not an object. Depending on the context, references can be just alias the compiler removes the reference and just uses the identifier to mean whatever the original object meant (T const & r = *ptr;, any later use of r in the function can be replaced by *ptr, and r does not need to exist at runtime) or it might have to be implemented by keeping the address of the object that it aliases (consider storing a reference as a member of an object) --which is implemented as an autodereferenced pointer. Commented Nov 28, 2011 at 13:27
5

Non-const and const reference binding follow different rules

These are the rules of the C++ language:

  • an expression consisting of a literal number (12) is a "rvalue"
  • it is not permitted to create a non-const reference with a rvalue: int &ri = 12; is ill-formed
  • it is permitted to create a const reference with a rvalue: in this case, an unnamed object is created by the compiler; this object will persist as long as the reference itself exist.

You have to understand that these are C++ rules. They just are.

It is easy to invent a different language, say C++', with slightly different rules. In C++', it would be permitted to create a non-const reference with a rvalue. There is nothing inconsistent or impossible here.

But it would allow some risky code where the programmer might not get what he intended, and C++ designers rightly decided to avoid that risk.

0
1

References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.

EDIT::

I am thinking of

int &x = y;

as almost equivalent of

int* __px = &y;
#define x (*__px)

where __px is a fresh name, and the #define x works only inside the block containing the declaration of x reference.

8
  • 1
    Why you can, if the reference is const :) Commented Nov 28, 2011 at 8:58
  • But the poster's example was not const Commented Nov 28, 2011 at 8:59
  • Yes, I meant your wording "references are pointers to things which can change" - it's about non-cost references. Commented Nov 28, 2011 at 9:14
  • "References are "hidden pointers"" wrong "to things which can change" wrong "things which can change (lvalues)." wrong
    – curiousguy
    Commented Nov 28, 2011 at 9:18
  • @Loki: could you explain more? Commented Nov 28, 2011 at 9:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.