加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:50:00 所属栏目:百科 来源:网络整理
导读:在与 this answer的评论帖子中提出的建议争论时,我遇到了一些代码,gcc4.8和VS2013拒绝编译,但是clang愉快地接受它并显示正确的结果. #include iostreamint main(){ int i{ 5 }; void* v = i; std::cout reinterpret_castint(*v) std::endl;} Live demo.GCC和
在与 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都因我预期的错误而失败,抱怨代码试图在reinterpret_cast中取消引用void *.所以我决定在标准中查看这个.来自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.

在这种情况下,T1为void,T2为int,并且可以使用reinterpret_cast将void *转换为int *.因此满足所有要求.

根据说明,reinterpret_cast< int&>(* v)与* reinterpret_cast< int *>(&(* v))具有相同的效果,根据我的推算,它与* reinterpret_cast< int相同* GT;(v)中. 那么这是一个海湾合作委员会和VC的错误,还是铿锵有力,我错误地解释了这个?

解决方法

void类型的表达式在return语句中只允许作为语法设备,并且你也可以将表达式转换为void,但这就是全部:没有类型为void的glvalues,void类型的表达式不引用内存.因此,从glvalue开始的标准引用的段落不适用.因此,铿锵是错的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读