为什么可以使用类型别名定义对引用的引用?
Why is it possible to define a reference to a reference using type alias?
既然不能定义对引用的引用,为什么这段代码第8行没有报错呢?我的理解是,上述声明等同于
double &&ref2 = value;
这应该会引发错误。
#include <iostream>
using namespace std;
int main()
{
double value = 12.79;
typedef double& ref_to_double;
ref_to_double ref = value; // Equivalent to double &ref = value;
ref_to_double &ref2 = value;
ref2 = 12.111;
cout << value << endl;
}
输出:
12.111
后续问题:将第 8 行替换为 ref_to_double &&ref2 = value;
也不会产生编译时错误。为什么会这样?
Why is it possible to define a reference to a reference using type alias?
is also not producing a compile-time error. Why is this so?
why is the 8th line of this code not throwing an error?
因为语言允许这样的表达式有效,所以没有其他解释......让我们从标准中拿一个很好的例子,来自 c++draft/Declarations/References:
int i;
typedef int& LRI;
typedef int&& RRI;
LRI& r1 = i; // r1 has the type int&
const LRI& r2 = i; // r2 has the type int&
const LRI&& r3 = i; // r3 has the type int&
RRI& r4 = i; // r4 has the type int&
RRI&& r5 = 5; // r5 has the type int&&
decltype(r2)& r6 = i; // r6 has the type int&
decltype(r2)&& r7 = i; // r7 has the type int&
既然不能定义对引用的引用,为什么这段代码第8行没有报错呢?我的理解是,上述声明等同于
double &&ref2 = value;
这应该会引发错误。
#include <iostream>
using namespace std;
int main()
{
double value = 12.79;
typedef double& ref_to_double;
ref_to_double ref = value; // Equivalent to double &ref = value;
ref_to_double &ref2 = value;
ref2 = 12.111;
cout << value << endl;
}
输出:
12.111
后续问题:将第 8 行替换为 ref_to_double &&ref2 = value;
也不会产生编译时错误。为什么会这样?
Why is it possible to define a reference to a reference using type alias?
is also not producing a compile-time error. Why is this so?
why is the 8th line of this code not throwing an error?
因为语言允许这样的表达式有效,所以没有其他解释......让我们从标准中拿一个很好的例子,来自 c++draft/Declarations/References:
int i;
typedef int& LRI;
typedef int&& RRI;
LRI& r1 = i; // r1 has the type int&
const LRI& r2 = i; // r2 has the type int&
const LRI&& r3 = i; // r3 has the type int&
RRI& r4 = i; // r4 has the type int&
RRI&& r5 = 5; // r5 has the type int&&
decltype(r2)& r6 = i; // r6 has the type int&
decltype(r2)&& r7 = i; // r7 has the type int&