通过void*和reinterpret_cast从字节字段读取

Mic*_*ael 1 c++ pointers void-pointers reinterpret-cast

我计划Tvoid*以下方式给出的字节字段中读取一个类型:

template <class T>
T read(void* ptr){
    return reinterpret_cast<T>(*ptr);
}
Run Code Online (Sandbox Code Playgroud)

但我有些疑惑:解除引用void*实际上是reinterpret_cast<T>什么?只是那个位置的字节?或"神奇地"长度的字节序列T?我应该先void*投入一个T*吗?

Bar*_*rry 5

您不能取消引用void指针,它不指向对象.但C标准规定:

指针void可以转换为指向任何对象类型的指针.

我们可以先转换ptrT*,然后取消对它的引用:

template <class T>
T read(void* ptr) {
    return *static_cast<T*>(ptr);
}
Run Code Online (Sandbox Code Playgroud)