What is the purpose of reinterpret
This question already has an answer here:
reinterpret_cast<T>()
forces a given bit-pattern to be interpreted as the type you desire. It is the most "brutal" among casts.
From 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.
In you example
template<typename T>
std::istream & read(std::istream* stream, T& value){
return stream->read(reinterpret_cast<char*>(&value), sizeof(T));
}
it is used to read from a given stream and cast the read data to char*
to treat it as a sequence of bytes (assuming char
is unsigned by default).
The read
function simply reads a number of bytes into a buffer, and the reinterpret_cast
here turns an arbitrary rvalue into such a buffer by overriding the actual type of the value. If the stream actually did contain a value of the correct type, the result is that this value is stored into value
.
上一篇: 动态的好处/用处是什么?
下一篇: 重新解释的目的是什么?