Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast any pointer to char poiner using static_cast

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*'
like image 590
ignorant Avatar asked Oct 22 '14 07:10

ignorant


Video Answer


1 Answers

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

like image 168
user657267 Avatar answered Sep 30 '22 06:09

user657267