#include <iostream>
using namespace std;
int main()
{
// Case 1
cout << &5; // This line fails to compile. Ok, I get this because "5" is a rvalue.
// Case 2
const int& ref = 5;
cout << &ref; // Works fine. Why?
// Case 3
cout << &"SomeString"; // Works fine. Ok, I get this because "SomeString" is a lvalue
return 0;
}
Why case 1 fails and case 2 passes? I could not find concrete explanation elsewhere. Most answers were confusing and self contradictory.
I understand that "5" in integer literal and it is a rvalue (we cannot take address of it) Then what special thing a const lvalue ref in case 2 doing, that it allows to take address of "5" ? As I have read, a reference (be it lvalue or rvalue) is just an alias. It has no address of its own.
A non-const lvalue reference cannot bind to a a temporary or a literal, and you cannot take the address of a literal or a temporary.
const lvalue references have lifetime extension when it binds to a temporary or a literal, basicaly
const int& ref = 5; // literal
Is interpreted by the compiler as
const int foo = 5;
const int& ref = foo;
You are getting back the address of the object whose lifetime was extended by the compiler. foo
Note that lifetime extension doesn't always apply, see Why doesn't a const reference extend the life of a temporary object passed via a function?, there are a few rules for when lifetime extension apply. (You need the rhs to be a temporary or a literal, not a reference to one, not an rvalue reference)
String literals are different, see C++ reference of a string literal, it is similar to lifetime extension that you can take their addresses, they are stored in static memory anyway, they are not temporaries, they exist beyond the scope of the function.