2 ms·
> Casting does not work as expected when optimization is turned on. > This is often caused by a violation of aliasing rules, which are part of the ISO C standa
by zamalek 12y ago
> Casting does not work as expected when optimization is turned on.
> This is often caused by a violation of aliasing rules, which are part of the ISO C standard. These rules say that a program is invalid if you try to access a variable through a pointer of an incompatible type.
Regarding this, is this what reinterpret_cast was at least partially designed for?
- pjmlp 12y agoKind of, casts in C++ were designed to be on your face, to call out that you are doing something unsafe. reinterpret_cast is meant to be really unsafe, to meant that in this type of casts the compiler will blindly do it, whereas the other *_cast there is still some type validation involved.
- zamalek 12y agoThanks for the clarification. So this doesn't signal to the compiler that it shouldn't optimize the aliased variables? Reason I ask and not test is that it seems that VC++ does not take advantage of this undefined behavior and the sample code always works 'as expected'.
- pjmlp 12y agoThis type of optimization is very compiler specific and can even change between versions of the same compiler. Actually this is the big difference between standard defined languages and those that rely on a single implementation. There is nothing to rely upon if it isn't defined in the standard as such.