Why are pointers to literals not possible

c++11pointersreference

Reference to a literal is possible only if the reference is declared as constant.

But why is a pointer to a const object not possible in case of literals?
i.e.

int const& ref = 5;//

But why is the same feature not available for a pointer, pointing to a constant object?

Best Answer

In the C++ view of the world, a literal does not occupy any memory. A literal just exists.

This view makes that there is no address for a pointer to refer to when it would point to a literal and for that reason, pointers to literals are forbidden.

Const references are actually the exception here in that they allow apparent indirect access to a literal. What happens underneath is that the compiler creates a temporary object for the reference to refer to and that temporary object is initialized with the value of the reference.

This creating of a temporary that the reference gets bound to is only allowed for const references (and gets used in other scenarios as well, not only for literals), because that is the only case where a reference/pointer to a temporary won't have undesired side-effects.