【问题标题】:why (var) is considered as lvalue?为什么 (var) 被认为是左值?
【发布时间】:2021-02-16 03:08:37
【问题描述】:

我试图通过堆栈溢出问题之一来理解 C++ 中的 decltype What is decltype and how is it used?

部分接受的答案如下。

int foo();
int n = 10;

decltype(n) a = 20;             // a is an "int" [id-expression]

decltype((n)) b = a;            // b is an "int &" [(n) is an lvalue]

decltype(foo()) c = foo();      // c is an "int" [rvalue]

decltype(foo()) && r1 = foo();  // int &&
decltype((n)) && r2 = n;        // int & [& && collapses to &]

我无法理解下面的陈述。

decltype((n)) b = a; // b 是 "int &" [(n) 是左值]

谁能告诉我为什么 (n) 被认为是左值。

【问题讨论】:

  • n是左值,括号不改变值类别
  • @MM,按照这个逻辑,在语句 decltype(n) a = 20 中,n 应该被视为左值。但这里 a 是一个 int。不是 int &。
  • 这实际上是 decltype(n) 的特殊之处 - 标准有一个特殊情况,当参数是一个未附加的 id 表达式时,它会丢弃“左值”。
  • decltype(n) 中没有 (n) 表达式。语法是decltype( 表达式或id ),而不是decltype 表达式
  • @MM:知道了。您能否将其发布为答案。我会接受的。

标签: c++ c++11


【解决方案1】:

(n)int 类型的左值,因此decltype((n))int&。现在,n 也是 int 类型的左值 - 但是在 decltype 的定义中有一个特殊情况,因为它的参数是一个未加括号的 id-expression,这使得 decltype(n)int 出现。

[dcl.type.simple]/4 对于表达式edecltype(e)表示的类型定义如下:
...
(4.2) — 否则,如果 e 是无括号的 id-expression 或无括号的类成员访问 (8.2.5),则 decltype(e) 是由 e 命名的实体的类型。 ..;
...
(4.4) — 否则,如果e 是左值,则decltype(e)T&,其中Te 的类型...

【讨论】:

    【解决方案2】:

    表达式n 是一个左值;并且在表达式周围加上括号不会改变值类别。

    the question already linked中所述:

    • decltype( (n) ) 是语法 decltype( expression )
    • decltype( n ) 是语法 decltype( id )

    后者不是decltype expression 表达式为(n),没有这样的语法。

    【讨论】:

      【解决方案3】:

      将表达式(n)n+0n*1n|0 进行比较可能会很有见地。都是表达式,所有这些表达式的值都与n 相同。所有这些表达式都是左值。

      【讨论】:

        猜你喜欢
        • 2015-03-08
        • 2019-08-04
        • 1970-01-01
        • 2014-11-27
        • 2017-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多