How is it possible for a const T& to refer to a literal?

68 Views Asked by At

My understanding is that a const T& is internally implemented via a const T *const. If so, how is the below code valid (since we cannot take the address of 7)?

const int& i = 7;

Or does the compiler does some trick here? If so, what?

1

There are 1 best solutions below

0
On

You cannot take the address of a literal like 7 but you can take the address of a temporary object whose value is 7.

Think of that line to be equivalent to

const int unnamed_temprary_variable = 7;
const int& i = unnamed_temprary_variable;

Or does the compiler does some trick here? If so, what?

The compiler does something analogous to the two lines I mentioned but it is not a trick. It is required by the language.

Searching for "extending the lifetime of temporaries" in SO resulted in a long list.