Why Doesn’t reinterpret_cast Force copy_n for Casts between Same-Sized Types?

why doesn’t reinterpret_cast handle that for me? One reason is that the size, alignment, and bit representations aren’t specified, so such a conversion wouldn’t be portable. However, that wouldn’t really justify making the behaviour undefined, just implementation-defined. By making it undefined, the compiler is allowed to assume that expressions of unrelated types don’t access the … Read more

C++ When should we prefer to use a two chained static_cast over reinterpret_cast

reinterpret_cast should be a huge flashing symbol that says THIS LOOKS CRAZY BUT I KNOW WHAT I’M DOING. Don’t use it just out of laziness. reinterpret_cast means “treat these bits as …” Chained static casts are not the same because they may modify their targets according to the inheritence lattice. struct A { int x; … Read more

What’s the best way to cast a function pointer from one type to another?

I think C/C++ are lacking a generic function pointer type, like void* as a generic object pointer type. Generally, converting from one function pointer into another is supported, provided that you don’t call the wrong function pointer type. See [expr.reinterpret.cast]/6: A function pointer can be explicitly converted to a function pointer of a different type. … Read more

Is it a strict aliasing violation to alias a struct as its first member?

The behaviour of the cast comes down to [expr.static.cast]/13; 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 … Read more

Why can’t I static_cast between char * and unsigned char *?

They are completely different types see standard: 3.9.1 Fundamental types [basic.fundamental] 1 Objects declared as characters char) shall be large enough to store any member of the implementation’s basic character set. If a character from this set is stored in a character object, the integral value of that character object is equal to the value … Read more

reinterpret_cast from object to first member

Yes, because both classes here are standard-layout types, you can convert between &b and &b.a. reinterpret_cast<A*>(p) is defined to be the same as static_cast<A*>(static_cast<void*>(p)), (5.2.10p7) so both your questions are equivalent. For standard-layout classes, the address of the struct/class is the same as the address of its first non-static member (9.2p19). And static_cast to/from void* … Read more