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"?
来自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 aschar* toint* , or >One_class* toUnrelated_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)); } |
它用于从给定的流中读取数据,并将读取的数据强制转换到