To do this, it will be enough to take the offset of this field from the beginning of the structure without any intermediate pointers (it is assumed that the structure is the standard layout type):
::std::memcpy(::std::addressof(i), _buf + _offset + offsetof(S, i), sizeof(i));
As for the attempt to convert a pointer to an object with a less strict alignment to a pointer to an object with a more strict alignment, in C ++ the behavior is not specified (that is, it is specified by the implementation):
8.5.1.10 Reinterpret cast [expr.reinterpret.cast]
7 An object pointer of a different type. 73 When the pointer is static_cast<cv T*>(static_cast<cv void*>(v))
, the result is static_cast<cv T*>(static_cast<cv void*>(v))
. [Note: Conversion of the “ T1
” to the type “of the pointer to the T2
” (where T1
and T2
are the types of t1) yields the original pointer value. —End note]
8.5.1.9 Static cast [expr.static.cast]
13 A prvalue of the type “pointer to cv1 void
” can be converted to a prvalue of the type “pointer to cv2 T
”, where is the cv-qualification as, or greater cv-qualification than, cv1 . It is not the case that the original pointer represents the value of the text, and the resulting pointer value is unspecified. Otherwise, if there is a pointer to it, it’s a pointer to interconvertible (6.7.2). Otherwise, the pointer value is unchanged by the conversion.
But to use the received pointer to the structure (even if the implementation correctly performs the address translation) to obtain a pointer to the field of this structure will already be undefined behavior .
int *
on an unlinedint
probably gives UB (by analogy with stackoverflow.com/a/28895321/2752075 ), but I don’t have exact references to the standard. - HolyBlackCat