Naturally, this won’t compile:
int &z = 3; // error: invalid initialization of non-const reference ....
and this will compile:
const int &z = 3; // OK
Now, consider:
const int y = 3;
int && yrr = y; // const error (as you would expect)
int && yrr = move(y); // const error (as you would expect)
But these next lines do compile for me. I think it shouldn’t.
int && w = 3;
int && yrr = move(3);
void bar(int && x) {x = 10;}
bar(3);
Wouldn’t those last two lines allow the literal 3 to be modified? What is the difference between 3 and a const int? And finally, Is there any danger with ‘modifying’ literals?
(g++-4.6 (GCC) 4.6.2 with -std=gnu++0x -Wall -Wextra)
The rvalue reference to the literal
3:is actually bound to a temporary that is the result of evaluating the expression
3. It’s not bound to some Platonic literal 3.(all the following standards references are from the March 2011 draft, n3242)
3.10/1 “Lvalues and rvalues”
Then 8.5.3 “References” gives the rules for how a reference is bound falls through to the last case, which says:
and gives as one example something very close to what’s in your question: