Back at the beginning of my C++ days (a lot of hair ago) I was surrounded by Java academics. When asked for an advantage of C++ over Java (typically a question I try to dismiss as contrived, but there you go), I'd include in my answer that C++ gave you references and pointers. The Java guys would look incredulous and suggest that references are pointers, and laugh me out of the room. I insisted that references and pointers are distinct in C++.
And, to be fair, I was right. References and pointers are different semantically and syntactically. Unfortunately, I backed up my claim with a fallacy: that the underlying implementation was different.
It was my firm belief that references were, by standardisation, name aliases in the syntax in the same way that a typedef
is a type alias with no storage.
I was sure that references were not objects and had no storage, that they just provided multiple top-level mappings of "name" to "object". In that regard, I thought that they were like soft-links in a filesystem:
Code: int a = 3; int& b = a;
Names Objects Memory
+-----+ +-------------+ +-------+
| a |---->| | | |
+-----+ | | | |
| int |---->| 3 |
+-----+ | | | |
| b |---->| | | |
+-----+ +-------------+ +-------+
Of course, although optimisations may lead to this, references do have storage. They are distinct objects, even if the syntax does its best to abstract that away from the programmer.
Suffice it to say, I was disappointed to learn that a compiler with optimisations turned off may implement a reference as a pointer, requiring a dereference operation: that I was actually creating the analogy to a hard-link in a filesystem:
Code: int a = 3; int& b = a;
Names Objects Memory
+-----+ +-------------+ +-------+
| a |---->| int |---->| |
+-----+ +-------------+ | |
| 3 |
+-----+ +-------------+ | |
| b |---->| int& |---->| |
+-----+ +-------------+ +-------+
Standard C++ doesn't actually specify how references ought to be implemented, so my theory could hold true for some toolchains, but it doesn't in any mainstream compiler... and it's certainly not stated in the standard.