Aliasing `T*` with `char*` is allowed. Is it also allowed the other way around?
- by StackedCrooked
Note: This question has been renamed and reduced to make it more focused and readable. Most of the comments refer to the old text.
According to the standard objects of different type may not share the same memory location. So this would not be legal:
int i = 0;
short * s = reinterpret_cast<short*>(&i); // BAD!
The standard however allows an exception to this rule: any object may be accessed through a pointer to char or unsigned char:
int i = 0;
char * c = reinterpret_cast<char*>(&i); // OK
However, it is not clear to me if this is also allowed the other way around. For example:
char * c = read_socket(...);
unsigned * u = reinterpret_cast<unsigned*>(c); // huh?
Summary of the answers
The answer is NO for two reasons:
You an only access an existing object as char*. There is no object in my sample code, only a byte buffer.
The pointer address may not have the right alignment for the target object. In that case dereferencing it would result in undefined behavior. On the Intel and AMD platforms it will result performance overhead. On ARM it will trigger a CPU trap and your program will be terminated!
This is a simplified explanation. For more detailed information see answers by @Luc Danton, @Cheers and hth. - Alf and @David Rodríguez.