cplusplus / CWG

Core Working Group
23 stars 7 forks source link

CWG2814 [expr.static.cast] Alignment requirement of class type without definition #444

Open randomnetcat opened 11 months ago

randomnetcat commented 11 months ago

Full name of submitter (unless configured in github; will be published with the issue): Janet Cobb

Reference: [expr.static.cast]

Issue description:

[expr.static.cast]/14 reads:

A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement of T, then the resulting pointer value is unspecified. Otherwise, if the original pointer value points to an object a, and there is an object b of type similar to T that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.

Consider the following code:

struct X; // never defined

int i;
X* p = static_cast<X*>(static_cast<void*>(&i));

The result of the cast to void* is a pointer to i. In evaluating the second cast, we are required to observe the alignment requirement of X. Per [basic.align], "Object types have alignment requirements ([basic.fundamental], [basic.compound]) which place restrictions on the addresses at which an object of that type may be allocated.", so even a never-defined class type has an alignment requirement. Does this mean that there is no way to determine whether the above cast yields an unspecified value?

This is (as far as I can tell) the only way that the alignment requirement of a never-defined class could be observed.

jensmaurer commented 11 months ago

CWG2814