Search code examples
c++strict-aliasing

Can I form a C++ reference from a pointer of the wrong type?


If I have a pointer T* t and I use reinterpret_cast<T*>(&u) to point to some object u (which is not a T), I know that I cannot access u via t.

Therefore, I think that I cannot form T& rt from t, even if I don't perform any access through rt because:

  1. To form rt I would need to express *t in some way, which is an "access", and I am prohibited from doing this.

  2. I would be initializing a reference with something other than "a valid object".

Is this understanding correct?

(Edited to clarify that I am asking about whether rt can be formed from t.)


Solution

  • To form rt I would need to express *t in some way, which is an "access", and I am prohibited from doing this.

    No, dereferencing itself is not an access. An access would require reading from or writing to a scalar object.

    I would be initializing a reference with something other than "a valid object".

    If t points to an object (whether with the correct type or not), there is nothing prohibiting binding a reference to the lvalue *t.

    However, you must assure that t does actually point to an object. Specifically you need to assure that u is aligned suitably for the type T. Otherwise the result of reinterpret_cast<T*>(&u) will have an unspecified value, instead of pointing to u (or an object pointer-interconvertible with it) as expected.

    In any case, of course, you are not generally allowed to use the resulting reference to read from or write to the object, to access members, etc.