我是 C++ 的新手,正在阅读如下代码:
template<typename T>
std::istream & read(std::istream* stream, T& value){
return stream->read(reinterpret_cast<char*>(&value), sizeof(T));
}
并调用它:
size_t size;
read(&stream, size);
谁能解释一下这里使用的 reinterpret_cast 的目的是什么以及调用 read 函数后的结果是什么?
更新:
问题是:
如果流中包含一个字符串,例如“test”,在调用 read 后,值的类型变为 char *,其内容为“test”?
reinterpret_cast<T>()
强制将给定的位模式解释为您想要的类型。这是 Actor 中最“残酷”的。
来自 MSDN :
Allows any pointer to be converted into any other pointer type. Also allows any integral >type to be converted into any pointer type and vice versa.
Misuse of the reinterpret_cast operator can easily be unsafe. Unless the desired >conversion is inherently low-level, you should use one of the other cast operators.
The reinterpret_cast operator can be used for conversions such as char*
to int*
, or >One_class*
to Unrelated_class*
, which are inherently unsafe.
The result of a reinterpret_cast
cannot safely be used for anything other than being >cast back to its original type. Other uses are, at best, nonportable.
以你为例
template<typename T>
std::istream & read(std::istream* stream, T& value){
return stream->read(reinterpret_cast<char*>(&value), sizeof(T));
}
它用于从给定的流中读取并将读取的数据转换为 char*
将其视为一个字节序列(假设 char
默认是无符号的)。