Sample code:
struct S { int x; };
int func()
{
S s{2};
return (int &)s; // Equivalent to *reinterpret_cast(&s)
}
>
I think it's in expr.reinterpret.cast#11
A glvalue expression of type T1, designating an object
x
, can be cast to the type “reference to T2” if an expression of type “pointer to T1” can be explicitly converted to the type “pointer to T2” using a reinterpret_cast. The result is that of*reinterpret_cast
where(p) p
is a pointer tox
of type “pointer to T1”. No temporary is created, no copy is made, and no constructors or conversion functions are called [1].
[1] This is sometimes referred to as a type pun when the result refers to the same object as the source glvalue
Supporting @M.M's answer about pointer-incovertible:
from cppreference:
Assuming that alignment requirements are met, a
reinterpret_cast
does not change the value of a pointer outside of a few limited cases dealing with pointer-interconvertible objects:
struct S { int a; } s;
int* p = reinterpret_cast(&s); // value of p is "pointer to s.a" because s.a
// and s are pointer-interconvertible
*p = 2; // s.a is also 2
versus
struct S { int a; };
S s{2};
int i = (int &)s; // Equivalent to *reinterpret_cast(&s)
// i doesn't change S.a;