I can't understand the quote (specifically, the bold part):
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.
int i = 0;
void *vp = &i;
auto *res = static_cast<double*>(vp);
My questions are:
does the address pointed by
res
(address ofint
) satisfy the alignment requirement ofdouble
?does the resulting pointer
res
has an unspecified value?And when I have something like this:
static_cast<double*>(static_cast<void *>(&i))
Doesi
type is not stricter than the target typedouble
? so that the result of this expression is not unspecified
CodePudding user response:
does the address pointed by res (address of int) satisfy the alignment requirement of double?
That would depend on the implementation. Most likely it doesn't. Typically the alignment requirement of int
is smaller than that of double
.
For example on the x86-64 System V ABI used e.g. on Linux, int
has alignment requirement 4
and double
has 8
.
You can check that the alignment requirement is satisfied for example with the following static_assert
:
static_assert(alignof(int) >= alignof(double));
does the resulting pointer res has an unspecified value?
If the alignment requirement is not fulfilled (i.e. the static_assert
fails), yes. Otherwise it will point to the object i
.
And when I have something like this: static_cast<double*>(static_cast<void *>(&i))
This is exactly equivalent to what is shown in the snippet.
Note that even if the alignment requirements are satisfied, res
cannot be used to access the value of the object it points to, because that would violate the pointer aliasing rules. So the result of the cast is very likely not useful for anything.