c++ - 将_cast 重新解释为 void 是否合法*

标签 c++ pointers void-pointers reinterpret-cast double-pointer

我在看 https://en.cppreference.com/w/cpp/language/reinterpret_cast我注意到它指定了我们始终可以转换为的合法类型:

  • 字节*
  • char*
  • unsigned char*

但是我没有在列表中看到void*。这是疏忽吗?我的用例需要 reinterpret_cast,因为我正在从 int** 转换为 void*。我最终将从 void* 转换回 int**

最佳答案

这些类型不受严格的别名规则约束。这并不意味着它们是您可以与 reinterpret_cast 一起使用的唯一类型.在将对象指针转换为另一种对象指针类型的情况下,不满足严格别名规则的要求意味着您无法安全地取消引用结果。但是您仍然可以安全地将结果指针转换回原始类型,并像使用原始指针一样使用结果。

reinterpret_cast 上 cppreference 的相关部分:

(Any object pointer type T1* can be converted to another object pointer type cv T2*. This is exactly equivalent to static_cast<cv T2*>(static_cast<cv void*>(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)

当转换回原始类型时,AliasedTypeDynamicType是相同的,所以它们是相似的,这是别名规则列出的第一个可以合法取消引用 reinterpret_cast 的结果的情况。 :

Whenever an attempt is made to read or modify the stored value of an object of type DynamicType through a glvalue of type AliasedType, the behavior is undefined unless one of the following is true:

  • AliasedType and DynamicType are similar.
  • AliasedType is the (possibly cv-qualified) signed or unsigned variant of DynamicType.
  • AliasedType is std::byte, (since C++17)char, or unsigned char: this permits examination of the object representation of any object as an array of bytes.

关于c++ - 将_cast 重新解释为 void 是否合法*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55728740/

相关文章:

c++ - 如何将一个 cpp 包含在另一个 cpp 中,例如复制粘贴而不是声明方式?

c++ - 如何从双指针获取值?

c - C 中 void * 转为 char 或 int

c++ - 为什么 `(void *)&` 会得到变量的地址?

c++ - 读取 char * 始终具有相同的地址

c++ - 当函数需要是成员函数时

c++ - 在不复制的情况下划分 std::string

c++ - CPP - 编译错误 (G++)

c - argc、argv 及其用法的有趣观察

c++ - 如何删除属于指针对象的指针 vector 中的项目