c++ - reinterpret_cast 的目的是什么

标签 c++

<分区>

我是 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 默认是无符号的)。

关于c++ - reinterpret_cast 的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16756594/

相关文章:

C++ lambda 不会对按值捕获的成员调用析构函数

c++ - STL 插入迭代器

c++ - 如何检查正在运行的进程以查看它正在使用哪些共享库?

c++ - 使用相同的 boost::accumulator_set 计算加权和未加权统计信息?

c++ - 如何通过引用将 vector 分配给对象?

c++ - 从 Windows cmd 调用 MSYS bash

c++ - c/c++如何实现异步写入?

c++ - 数组和比较的问题……在 if 的下面放什么来让僵尸在每一轮都向 sp 移动?

c++ - 我的 GUI 模板化小部件系统出现问题

c++ - 资源管理器上下文菜单的 Shell 扩展,图标打破了经典 Windows 设计中的对齐方式