Reputation: 147
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*'
Upvotes: 6
Views: 3810
Reputation: 21000
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 from2 void*
(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
Upvotes: 7