Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ idempotence of going through: pointer → reference → pointer

My understanding

  • 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.

Question

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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".

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading