The expression
TYPE& == *(TYPE const *)
looks a bit of domain error as TYPE&
is a type while *(TYPE const*)
looks like an expression applied to a type. At the very least, the right hand side should be const
pointer rather than a pointer to const
, i.e.:
A TYPE&
behaves like an auto-dereferenced immutable pointer, something like *(TYPE* const)
with the implicit constraint that the pointer cannot be null.
The compiler does recognize references and in some cases, namely when binding temporaries to a reference to a const
object (T const&
) at function scope: the life-time of the temporary gets expanded until the reference goes out of scope! For example:
{
std::string const& s = std::string("longer lived");
// the original temporary created above still lives
} // <-- ... and gets destroyed when s goes out of scope here
Another major difference between pointers and references are semantics when it comes to operator overloading: pointers are consider built-in types and operators only involving built-in types cannot be overloaded. A reference of type T&
behaves like a T
object, i.e., overloaded operators for T&
are considered. That is, while the a T&
is identical to using a T* const
from a representation point of view, the compiler understands the difference and treats the entities differently on a semantic level.