Search code examples
c++pointersvoid-pointersreinterpret-cast

Reading from a byte field by void* and reinterpret_cast


I plan to read a type T from a byte field given by a void* the following way:

template <class T>
T read(void* ptr){
    return reinterpret_cast<T>(*ptr);
}

But I get some doubts: What does dereferencing a void* actually give into reinterpret_cast<T>? Just the byte at that position? Or 'magically' a byte sequence of the length of T? Should I first cast the void* into a T*?


Solution

  • You cannot dereference a void pointer, it does not point to an object. But the C standard dictatetes that:

    A pointer to void may be converted to or from a pointer to any object type.

    We can first convert ptr to a T* and then dereference it:

    template <class T>
    T read(void* ptr) {
        return *static_cast<T*>(ptr);
    }