If according to strict aliasing rule char pointer may point to any type pointer, then why can't I cast any-type pointer to char pointer using static_cast?
char *ptr;
int *intPtr;
ptr = reinterpret_cast<char*>(intPtr); // ok
ptr = static_cast<char*>(intPtr); // error: invalid static_cast from type 'int*' to type 'char*'
How static_cast
works is unrelated to the strict aliasing rule.
static_cast
will not allow you to cast between arbitrary pointer types, it can only be used to cast to1 and from2void*
(and casting to void*
is usually superfluous as the conversion is already implicit3).
You could do this
ptr = static_cast<char*>(static_cast<void*>(intPtr));
but there is absolutely no difference4 between that and
ptr = reinterpret_cast<char*>(intPtr);
https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf
1[expr.static.cast] / 6
2[expr.static.cast] / 13
3[conv.ptr] / 2
4[expr.reinterpret.cast] / 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With