Is it UB to reinterpret_cast a T* to a uintptr_t, reinterpret_cast that uintptr_t to a void*, then static_cast that void* back to a T*?

507 views Asked by At

I am writing a C++ tagged pointer. I have a question about whether the operations I use to implement its basic functionality cause undefined behavior:

  • When constructing a tagged pointer given a pointer T*, I reinterpret_cast the pointer to a uintptr_t. This allows me to perform bitwise operations on the memory address, which are necessary to add/extract/inspect the tag.
  • When the user requests the original pointer back, I use reinterpret_cast to cast the uintptr_t to a void* (after removing the tag). If a pointer to a specific type is needed, I take that void* and static_cast it to T* (assuming T is indeed the type held within the tagged pointer).

So, in summary, I am performing the following transformations on a T*:

  • reinterpret_casting the T* to a uintptr_t
  • Later, reinterpret_casting that uintptr_t to a void*, and possibly static_casting that void* back to a T*.

Does any of this result in undefined behavior? Additionally, am I using reinterpret_cast and static_cast correctly, in their intended use cases?

0

There are 0 answers