Hacker News new | ask | show | jobs
by wilun 2938 days ago
Stop spreading complete bullshit and go read https://en.cppreference.com/w/cpp/language/reinterpret_cast already. C++ has strict aliasing rules (probably even stricter than C) and reinterpret_cast can do absolutely nothing to workaround them. It is of no help because it certainly not allow you to access objects with a wrong type. It merely reinterpret the type of values, or values as far as the implementation is concerned (C++ reference, which are only pointers with syntactic sugar plus a few extra restrictions). In the C++ community, the current thinking is that memcpy allows to type pun, but IIRC the C++ standard is actually not even clear as for why this is the case, and in its current writing it might be that there is actually no way. Short of memcpy you need at least a placement new on a trivial type. And sometimes even other cases of insanity, like std::launder. Hell, sometimes you even need std::launder for the same type.

Short of converting void* (or sufficiently large ints) to T* because of legacy API, I'm not sure reinterpret_cast has any portable use. But I'm sure you can NOT type pun with it if that would break the aliasing rules.

1 comments

Note: When converting void* to T* you can use use static_cast, which is well-defined. For example

    int* x = static_cast<int*>(malloc(sizeof(int)));
BTW, I find this useful when programming in a C dialect that compiles as C:

  #ifdef __cplusplus
  #define strip_qual(TYPE, EXPR) (const_cast<TYPE>(EXPR))
  #define convert(TYPE, EXPR) (static_cast<TYPE>(EXPR))
  #define coerce(TYPE, EXPR) (reinterpret_cast<TYPE>(EXPR))
  #else
  #define strip_qual(TYPE, EXPR) ((TYPE) (EXPR))
  #define convert(TYPE, EXPR) ((TYPE) (EXPR))
  #define coerce(TYPE, EXPR) ((TYPE) (EXPR))
  #endif
Very cool; you just use these macros for all your casts, and when building using a C++ compiler, you get additional diagnostics, like that you're accidentally stripping away a const-qualifier.
You just re-invented MFC macros for the C++ features that were being discussed for ISO C++89.

https://docs.microsoft.com/en-us/cpp/mfc/reference/mfc-macro...