gpt4 book ai didi

c++ - reinterpret_cast 是如何工作的?

转载 作者:搜寻专家 更新时间:2023-10-31 00:09:03 24 4
gpt4 key购买 nike

我想知道 reinterpret_cast 在幕后是如何工作的。我正在从一本书中了解它,但我就是不明白。例如。假设我有以下代码部分:

int a = 255;
char *pChar = reinterpret_cast<char*>(&a);

std::string str = "Hello";
char *pChar = reinterpret_cast<char*>(&str);

pChar 在这两个示例中将指向什么,为什么我在尝试打印它们的内容时看不到任何内容,当然还有 reinterpret_cast 是如何工作的?

编辑:我知道 reinterpret_cast 使用起来非常危险,只想用它来将字节从内存块直接写入二进制文件。我不明白的是,当我有一个

int a = 255; (00 00 00 FF in memory)

我想将变量 a 视为一系列字节,char* :

char *pChar = reinterpret_cast<char*>(&a);

pChar 会指向变量a (00 00 00 FF) 的各个字节吗?

所以当我想将 pChar 指向的内容写入二进制文件时:

a_file.write(reinterpret_cast<char*>(&a), sizeof(a));

它写入变量 a 的各个字节,对吗?

最佳答案

它在运行时不做任何事情。 Cpp reference :

Unlike static_cast, but like const_cast, the reinterpret_cast expression does not compile to any CPU instructions. It is purely a compiler directive which instructs the compiler to treat the sequence of bits (object representation) of expression as if it had the type new_type.

你的两个转换都非常危险,因为第一个指针指向一个 int,它可能在内存中表示为 00 00 00 FF,因此不会打印任何内容,因为 00 == '\0',这是字符串结尾字符。这假设您使用的是大端机器。如果这是一个用非零值填充所有字节的 int,您将无限期地读到该位置的末尾。

第二个告诉编译器将 string 所在的位置视为 char*,这不是实际字符串内容的起始地址,而是一个实现定义的结构,其中可能包含大小、容量和指针变量或用于小字符串优化的字符串表示。由于大小和容量通常为 64 位宽,并且大小和容量可能都小于 2^32,因此您可能会遇到零字节,因此不会打印任何内容。再一次,如果没有意外的零字节,您的读取将无限期地结束。

解决 OP 的编辑问题:

根据链接的 cpp 引用站点的第 5 节

Any pointer to object of type T1 can be converted to pointer to object of another type cv T2. This is exactly equivalent to static_cast(static_cast(expression)) (which implies that if T2's alignment requirement is not stricter than T1's, the value of the pointer does not change and conversion of the resulting pointer back to its original type yields the original value). In any case, the resulting pointer may only be dereferenced safely if allowed by the type aliasing rules (see below)

赋予如下:

When a pointer or reference to object whose dynamic type is DynamicType is reinterpret_cast (or C-style cast) to a pointer or reference to object of a different type AliasedType, the cast always succeeds, but the resulting pointer or reference may only be used to access the object if one of the following is true: ...

AliasedType is char, unsigned char, or std::byte: this permits examination of the object representation of any object as an array of bytes. ...

,指针应该指向a开始的地址。

关于c++ - reinterpret_cast 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45279901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com