gpt4 book ai didi

c++ - 取消引用 void 指针时的 reinterpret_cast 行为

转载 作者:太空狗 更新时间:2023-10-29 20:13:28 26 4
gpt4 key购买 nike

在与某人争论他在this answer的评论线程中提出的建议时,我遇到了一些 gcc4.8 和 VS2013 拒绝编译但 clang 愉快地接受它并显示正确结果的代码。

#include <iostream>

int main()
{
int i{ 5 };
void* v = &i;
std::cout << reinterpret_cast<int&>(*v) << std::endl;
}

Live demo . GCC 和 VC 都因我预期的错误而失败,提示代码试图取消引用 void*reinterpret_cast 内.所以我决定在标准中查找它。来自 N3797,§5.2.10/11 [expr.reinterpret.cast]

A glvalue expression of type T1 can be cast to the type “reference to T2” if an expression of type “pointer to T1” can be explicitly converted to the type “pointer to T2” using a reinterpret_cast. The result refers to the same object as the source glvalue, but with the specified type. [ Note: That is, for lvalues, a reference cast reinterpret_cast<T&>(x) has the same effect as the conversion *reinterpret_cast<T*>(&x) with the built-in & and * operators (and similarly for reinterpret_cast<T&&>(x)). —end note ] No temporary is created, no copy is made, and constructors (12.1) or conversion functions (12.3) are not called.

在这种情况下 T1voidT2int , 和一个 void*可以转换为int*使用 reinterpret_cast .所以所有要求都满足了。

根据注释,reinterpret_cast<int&>(*v)*reinterpret_cast<int*>(&(*v)) 效果相同,据我估计,与 *reinterpret_cast<int*>(v) 相同.

那么这是 GCC 和 VC 的错误,还是 clang 而我以某种方式误解了它?

最佳答案

void 类型的表达式被允许作为 return 语句中的主要语法设备,您也可以将表达式转换为 void,仅此而已:没有 void 类型的泛左值,void 类型的表达式不引用内存。因此,引用的标准中以 glvalue 开头的段落不适用。因此,clang 是错误的。

关于c++ - 取消引用 void 指针时的 reinterpret_cast 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21178903/

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