Mic*_*ael 1 c++ pointers void-pointers reinterpret-cast
我计划T从void*以下方式给出的字节字段中读取一个类型:
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*吗?
您不能取消引用void指针,它不指向对象.但C标准规定:
指针
void可以转换为指向任何对象类型的指针.
我们可以先转换ptr为T*和,然后取消对它的引用:
template <class T>
T read(void* ptr) {
return *static_cast<T*>(ptr);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |