我在看 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 cvT2*
. This is exactly equivalent tostatic_cast<cv T2*>(static_cast<cv void*>(expression))
(which implies that ifT2
's alignment requirement is not stricter thanT1
'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)
当转换回原始类型时,AliasedType
和 DynamicType
是相同的,所以它们是相似的,这是别名规则列出的第一个可以合法取消引用 reinterpret_cast
的结果的情况。 :
Whenever an attempt is made to read or modify the stored value of an object of type
DynamicType
through a glvalue of typeAliasedType
, the behavior is undefined unless one of the following is true:
AliasedType
andDynamicType
are similar.AliasedType
is the (possibly cv-qualified)signed
orunsigned
variant ofDynamicType
.AliasedType
isstd::byte
, (since C++17)char
, orunsigned 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/