为什么(int&)0格式错误? [英] Why is (int&)0 ill-formed?

查看:72
本文介绍了为什么(int&)0格式错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据[expr.cast]/4,C风格的强制转换按顺序尝试以下强制转换:

According to [expr.cast]/4, a C-style cast tries the following casts in order:

  1. const_cast
  2. static_cast
  3. static_cast 后跟 const_cast
  4. reinterpret_cast
  5. reinterpret_cast 后跟 const_cast
  1. const_cast
  2. static_cast
  3. static_cast followed by const_cast
  4. reinterpret_cast
  5. reinterpret_cast followed by const_cast

以下演员表的格式正确:

The following cast is well-formed:

const_cast<int&>(static_cast<const int&>(0))

GCC和Clang都拒绝强制转换(int&)0.为什么?

Yet both GCC and Clang reject the cast (int&)0. Why?

推荐答案

拒绝使用强制转换(int&)0的原因是,您试图将文字转换为没有实际意义的引用.&运算符需要一个可引用的值,并且您不能引用文字.编译器发现您正在将文字转换为右值,因此 main.cpp:2:11:错误:类型为'int'的右值表达式的无效类型转换为'int&'

The reason the cast (int&)0 is rejected is because you are trying to cast a literal as a reference which doesn't really make sense. The & operator expects a reference-able value and you cannot reference a literal. The compiler sees that you are casting a literal as an rvalue hence main.cpp:2:11: error: invalid cast of an rvalue expression of type 'int' to type 'int&'

这个问题并没有真正归结为强制类型转换,而是无法将文字强制转换为引用.

This question doesn't really come down to the hierarchy of casts but instead the inability to cast literals as references.

快速说明,您的措辞让我有些困惑,是 const_cast< int&(static_cast< const int&>(0)); 被编译器接受了吗?不应因为将左值转换为右值而导致.如果是这样,我一定是误解了这个问题,我会拒绝回答.

Quick note, I am a little confused by your wording, is const_cast<int&>(static_cast<const int&>(0)); accepted by the compiler? It shouldn't due to casting an lvalue as an rvalue. If so I must've misunderstood the question and I'll recuse my answer.

这篇关于为什么(int&amp;)0格式错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆