decltype((x))类型为什么是x的引用类型

C++语言 码拜 9年前 (2016-04-07) 1229次浏览
标准文档里面说,假如decltype的对象是一个表达式(x),那么得到的类型,假如x是int那么就是int&
不理解这个规则。做了个小实验

	int x = 1;
	decltype((x)) r = x;
	r = 3;
	cout << x << endl;

确实,x变成了3。本人的问题是”(x)”算是一个表达式(expression)吗,假如是的话,那么本人期待:

	decltype((1))i = x;
	i = 4;
	cout << x << endl;

这里”1″是一个int类型的常数,那么(1)能否也是个表达式? 假如是的话,decltype((1))能否因该也返回int&。但测试结果表明,不是这样,x没有变成4
为什么上面两个实验结果不同,到底怎么样理解(x)是一个表达式?

解决方案

15

The type denoted by decltype(e) is defined as follows:
if e is an lvalue, decltype(e) is T&, where T is the type of e;

30

2) If the argument is any other expression of type T, and
a) if the value category of expression is xvalue, then decltype yields T&&;
b) if the value category of expression is lvalue, then decltype yields T&;
c) if the value category of expression is prvalue, then decltype yields T.
仔细读:http://en.cppreference.com/w/cpp/language/decltype

10

额外加括号以后就是引用,标准规定的。

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明decltype((x))类型为什么是x的引用类型
喜欢 (0)
[1034331897@qq.com]
分享 (0)