如果 T1 在重新解释选角方面不比 T2 更严格,会发生什么情况?
[expr.reinterpret.cast]/7: 任何对象指针类型 T1* 都可以 转换为另一个对象指针类型 cv T2*。这正是 相当于 static_cast
(static_cast (T1_var)) (这意味着如果 T2 的对齐要求不比 T1的时候,指针的值没有改变并且转换了 返回到其原始类型的结果指针产生原始值)
我想知道使用reinterpret_cast
将指针从一种类型转换为另一种类型时没有限制吗 在阅读给定的引用时,我唯一注意到的是目标类型应比原始类型更严格,[否则]此引用中未提及。例如
int *p = 0;
double *q = reinterpret_cast<double *>(p)
,这里 alignof(int)
不大于(更严格?)等于 alignof(double)
。虽然编译器没有给出错误甚至警告,但我认为在这种情况下,q
指针持有一个未指定的值?取消引用它是未定义的行为。
那么这是否意味着将 T1*
类型的指针转换为 T2*
,只要 static_assert(alignof(T1) > ;=alignof(T2))
失败?
[expr.reinterpret.cast]/7:
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*>(T1_var))
(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)
Am I wondering that there's no limitation while casting a pointer from one type to another using reinterpret_cast
. The only thing I notice, when reading the given quote, is that the target type shall be stricter than the original type, [otherwise] not mentioned in this quote. For example
int *p = 0;
double *q = reinterpret_cast<double *>(p)
Here alignof(int)
is not greater (stricter?) than or equal alignof(double)
. Although the compiler gives no errors or even warnings, I think in this case, q
pointer holds an unspecified value? and dereferencing it is undefined behavior.
So does this mean converting a pointer of type T1*
into T2*
, the resulting pointer always has an unspecified value as long as static_assert(alignof(T1) >= alignof(T2))
fails?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不是真的。如果
T1
类型的实际地址不满足的对齐要求,结果只是(但总是)未指定T2
类型。它可能会这样做,在这种情况下,行为是明确定义的。您引用的标准中的段落指出了一个
reinterpret_cast
操作与两个static_cast
操作的等价性通过中间void*
指针。并且,根据标准,在上一节有关static_cast
的内容中(粗体是为了强调我的意思):Not really. The result is only (but always) unspecified if the actual address of the
T1
type doesn't fulfil the alignment requirements of theT2
type. It may do so, in which case the behaviour is well-defined.The paragraph from the Standard you cite states the equivalence of a
reinterpret_cast
operation to twostatic_cast
operations via an intermediatevoid*
pointer. And, from the Standard, in the previous section aboutstatic_cast
(bolding for emphasis mine):