简体   繁体   English

为什么(int&)0格式不正确?

[英]Why is (int&)0 ill-formed?

According to [expr.cast]/4, a C-style cast tries the following casts in order: 根据[expr.cast] / 4,C风格的强制转换按顺序尝试以下强制转换:

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

The following cast is well-formed: 以下演员表格很好:

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

Yet both GCC and Clang reject the cast (int&)0 . 然而,GCC和Clang都拒绝了演员阵容(int&)0 Why? 为什么?

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. cast(int&)0被拒绝的原因是因为你试图将一个文字作为一个真正有意义的引用。 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&' 编译器发现你正在将一个文字作为一个右值转换为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. 这个问题并没有真正归结为强制转换的层次结构,而是无法将文字作为引用。

Edit: Quick note, I am a little confused by your wording, is const_cast<int&>(static_cast<const int&>(0)); 编辑:快速注释,我对你的措辞有点困惑,是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. 如果是这样,我一定是误解了这个问题,我会回答我的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM