关于c ++:reinterpret_cast的目的是什么


What is the purpose of reinterpret_cast

本问题已经有最佳答案,请猛点这里访问。

我是C++新手,阅读一些代码如下:

1
2
3
4
template<typename T>
std::istream & read(std::istream* stream, T& value){
    return stream->read(reinterpret_cast<char*>(&value), sizeof(T));
}

并称之为:

1
2
size_t size;
read(&stream, size);

谁能解释一下这里使用的reinterpret-cast的目的是什么?调用read函数后的结果是什么?

更新:

问题是:

如果流包含字符串,例如"test",则在调用read之后,值的类型变为char*并且其内容为"test"?


reinterpret_cast()强制将给定的位模式解释为您想要的类型。这是最"野蛮"的演员。

来自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.

在你的例子中

1
2
3
4
template<typename T>
std::istream & read(std::istream* stream, T& value){
    return stream->read(reinterpret_cast<char*>(&value), sizeof(T));
}

它用于从给定的流中读取数据,并将读取的数据强制转换到char*中,以将其视为字节序列(假设char在默认情况下是无符号的)。


read函数简单地将若干字节读取到缓冲区中,这里的reinterpret_cast通过覆盖值的实际类型将任意右值转换为此类缓冲区。如果流确实包含正确类型的值,则结果是该值存储在value中。