Reputation: 41209
If we have this code:
int foo=100;
int& reference = foo;
int* pointer = &reference;
There's no actual binary difference in the reference's data and the pointer's data. (they both contain the location in memory of foo
)
part 2
So where do all the other differences between pointers and references (discussed here) come in? Does the compiler enforce them or are they actually different types of variables on the assemebly level? In other words, do the following produce the same assembly language?
foo=100;
int& reference=foo;
reference=5;
foo=100;
int* pointer=&foo;
*pointer=5;
Upvotes: 12
Views: 3497
Reputation: 1148
Just to amplify, while it might be true that references are the same as pointers under the hood on nearly all compilers, it is a serious mistake to depend on that behavior. Not only is it likely to bite you on the ass when you least expect it, but it's also incorrect use of references. If it's a pointer you need, use a pointer.
Upvotes: 0
Reputation: 41404
Theoretically, they could be implemented in different ways.
In practice, every compiler I've seen compiles pointers and references to the same machine code. The distinction is entirely at the language level.
But, like cdiggins says, you shouldn't depend on that generalization until you've verified it's true for your compiler and platform.
Upvotes: 20
Reputation: 18223
There is absolutely nothing reliable about the relationship between C++ code and what machine code a compiler generates.
Some people say "in my experience ... etc. etc. etc." but this is more unreliable than you may realize. Not many people have actual experience in any substantial cross-section of all the possible compiler/architecture combinations. [Edit: I think that Crashworks proves me wrong though. :-)]
Consider the following list of C++ compilers:
Now multiply this list by the following short list of machine architectures:
Now multiply by operating system and optimization flags, and you may find that everyone's experience is woefully lacking.
Upvotes: 10
Reputation: 2395
Pointers and references have different semantics in C++, but the code generated is the same.
Upvotes: 1