gpt4 book ai didi

c++ - reinterpret_cast 是否保证它永远不会改变其操作数的值?

转载 作者:行者123 更新时间:2023-11-30 01:54:07 26 4
gpt4 key购买 nike

#include <cassert>

struct A { int a; };
struct I1 : A { int a; };
struct I2 : A { int a; };
struct D : I1, I2 { int a; };

using namespace std;

int main()
{
auto d = new D;

auto a = static_cast<I2*>(d);
assert((void*)(a) != (void*)(d)); // OK

auto b = reinterpret_cast<I2*>(d);
assert((void*)(b) == (void*)(d)); // OK under VC++. Is it guaranteed?
}

reinterpret_cast 是否保证它永远不会改变其操作数的值?

最佳答案

Does reinterpret_cast guarantee it will never change the value of its operand?

TL;DR 我认为,在某些情况下。

保证只要目标类型的对齐要求不比源类型更严格。否则转换的效果是不确定的。


最简单的方法是询问标准,具体来说:§5.2.10 [expr.reinterpret.cast]

7/ An object pointer can be explicitly converted to an object pointer of a different type.70 When a prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”, the result is static_cast<cv T2*>(static_cast<cv void*>(v)) if both T1 and T2 are standard-layout types (3.9) and the alignment requirements of T2 are no stricter than those of T1, or if either type is void. Converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value. The result of any other such pointer conversion is unspecified.

在你的情况下因为没有virtual此层次结构中的方法,类型是标准布局类型。并且由于确实两者具有相同的对齐要求(因为它们包含相同的值),所以我们确实在此处匹配了明确指定的效果,因此:

reinterpret_cast<I2*>(d)

相当于:

static_cast<I2*>(static_cast<void*>(d))

因此我们需要回到§5.2.9 [expr.static.cast]:

7/ The inverse of any standard conversion sequence (Clause 4) not containing an lvalue-to-rvalue (4.1), array-to-pointer (4.2), function-to-pointer (4.3), null pointer (4.10), null member pointer (4.11), or boolean (4.12) conversion, can be performed explicitly using static_cast. A program is ill-formed if it uses static_cast to perform the inverse of an ill-formed standard conversion sequence.

T*void*是根据 §4.10 [conv.ptr] 第 2 段的标准转换序列;所以我假设这意味着 static_cast来自 void*T*应该产生相同的地址(假设它首先符合 T 的对齐要求)。

13/ A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T,” where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. The null pointer value is converted to the null pointer value of the destination type. A value of type pointer to object converted to “pointer to cv void” and back, possibly with different cv-qualification, shall have its original value. [ Example:

T* p1 = new T;
const T* p2 = static_cast<const T*>(static_cast<void*>(p1));
bool b = p1 == p2; // b will have the value true.

—end example ]

不幸的是,该示例已关闭(与您的情况相比);所以我们从中得不到太多。因为它是相关的,所以我只是为了完整性而引用它。

关于c++ - reinterpret_cast 是否保证它永远不会改变其操作数的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22371122/

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