What is the purpose of reinterpret

This question already has an answer here:

  • When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? 6 answers

  • 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 .

    链接地址: http://www.djcxy.com/p/28702.html

    上一篇: 动态的好处/用处是什么?

    下一篇: 重新解释的目的是什么?