In C++, an normal value can be converted to a pointer to itself using &value
, or to a reference to itself through implicit cast.
As opposed to Rust, references aren't actual first-class types but merely a binary qualifier that some type declaration sites accept. References can be used transparently as if they were their referee, hiding away the internal pointer1. As such, we can use &refToValue
to obtain a pointer to the referee immediately.
If I convert a pointer, to a reference, back to a pointer, am I guaranteed to get the original pointer back? This would be the case in Rust, but again, Rust has first-class references defined as "normal" types abstracting over a pointer.
// Sample code by @chi
T x;
T* ptr1 = &x;
T& ref = *ptr1;
T* ptr2 = &ref;
assert(ptr1 == ptr2); // Is that always true according to the spec?
1: I know that the C++ standard doesn't require references to be implemented as pointers, but I cannot see how they could be implemented in any other way (not considering context-specific optimizations), especially if the answer to my final question is "yes".
If I convert a pointer, to a reference, back to a pointer, am I guaranteed to get the original pointer back?
Yes.
references aren't actual first-class types ... binary qualifier that some type declaration sites accept
Indeed, while references are types, they can't serve as expression types.
So e.g. when you do &*foo
, *foo
isn't a reference.