Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Semantics in C++

While there are zillions of sources on clarifying the concept of references in C++, I'm trying to explain the concept of reference to someone who is familiar with pointers. In other words, I'm wondering whether the following semantic expression is ALWAYS true?

TYPE& == *(TYPE const *)

1 Answers

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.

like image 175
Dietmar Kühl Avatar answered Aug 03 '26 06:08

Dietmar Kühl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!