reinterpret_cast<char *> 是 reinterpret_cast 的唯一有效用法吗?

Is reinterpret_cast<char *> the only valid use of reinterpret_cast?

我最近了解到C++标准包含"strict aliasing rules",它禁止通过不同类型的变量引用相同的内存位置。

但是,该标准确实允许 char 类型合法地别名任何其他类型。这是否意味着 reinterpret_cast 在法律上只能用于转换为类型 char *char &

我相信严格的别名允许在继承层次结构中的类型之间进行转换,但我认为这些情况倾向于使用 dynamic_cast<>?

谢谢

您还可以使用 reinterpret_cast 将指针类型转换为整数类型:

char* ptr = /* ... */
uintptr_t ptrInt = reinterpret_cast<uintptr_t>(ptr);

您返回的特定整数值不可跨平台移植,但这是一个安全且定义明确的操作。

reinterpret_cast 有许多不同的用途。 cppreference page 列出了 11 种不同的情况。

我猜你只是问案例 5 和案例 6:将 T * 转换为 U *,将 T 转换为 U &

在这些情况下,只要没有对齐冲突,转换就是合法的。仅当您读取或写入生成的表达式时才会出现严格的别名问题。

你在第一段中对严格别名规则的总结过于简单化了,一般来说 U 有几种合法类型。同一个 cppreference 页面给出了案例的项目符号列表;您可以在 C++ 标准草案中阅读规则的确切文本。

reinterpret_cast还有其他有用的用途。

指向整数类型的指针

是的,有时候over想把指针的值存储成整数类型。

使用 C++ 样式转换执行此操作的唯一方法是使用 reinterpret_cast

示例:

auto pointerValue = reinterpret_cast<std::uintptr_t>(pointer);

在原始内存块中存储对象

有时您想将数据存储在堆栈上,但稍后再对其进行初始化。使用动态分配和指针不会使用堆栈。 std::aligned_storage 作为原始对齐内存块做得很好。

struct MyStruct {
    int n;
    std::string s;
};

// allocated on automatic storage
std::aligned_storage<sizeof(MyStruct), alignof(MyStruct)>::type storage;

// actually initialize the object
new (&storage) MyStruct;

// using the object
reinterpret_cast<MyStruct*>(&storage)->n = 42;

我敢肯定还有很多我不知道的其他用途,但这些是我已经用过的。