简体   繁体   English

C ++ 11:decltype((x))和decltype((x + 1))的类型不同吗?

[英]C++11: the type of decltype((x)) and decltype((x+1)) are different?

I was thinking that decltype((x)) give the & reference type, but some experiment showed sth else: 我以为decltype((x))给出了&引用类型,但是一些实验表明还有其他问题:

#include<stdio.h>
int main(){
    int x = 0;
    decltype((x)) r = x;
    r = 1;
    printf("%d\n",x);

    decltype((x+1)) i = x;
    i = 2;
    printf("%d\n",x);

    decltype((1)) k = x;
    k = 3;
    printf("%d\n",x);
    return 0;
}

I was expecting that (x) and (x+1) and (1) woul all give an "int&". 我期望(x)和(x + 1)以及(1)都给出一个“ int&”。 However the running result was 但是运行结果是

1
1
1

I expected that the running result should be 1,2,3 as each decltype retrieves reference, but seems only the 1st works, while both (x+1) an (1) gives only int, not 'int&'. 我希望运行结果应该是1,2,3,因为每个decltype都检索引用,但是似乎只有第1个有效,而(x + 1)和(1)都只给出了int,而不是'int&'。 Why, are (x) and (x+1) of different id-expression type? 为什么(x)和(x + 1)具有不同的id表达式类型?

x + 1 is a prvalue, so its decltype is just int . x + 1是一个prvalue,因此其decltype只是int By contrast, x is an id-expression, and so (x) is an lvalue and its decltype is int& . 相比之下, x是id表达式,因此(x)是左值,其decltype是int& (There is a special rule by which the decltype of an id-expression itself (eg x ) is the actual type as which the variable was declared, and you have to parenthesize the expression to get at the value category of the expression.) (有一个特殊的规则,id表达式本身的十进制类型(例如x )是声明变量的实际类型,并且必须在表达式中加上括号以获取表达式的值类别。)

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

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