【发布时间】:2022-07-28 23:25:39
【问题描述】:
我正在使用here 列出的资源学习 C++。我遇到了以下claim,我认为这是不正确的:
typedef int& A; const A aref = 3;因为它相当于
int & const aref = 3;
正如你在上面的代码 sn-p 中看到的,用户声称const A aref 等同于int & const aref。现在,我的问题是上述说法在技术上正确吗?
我不这么认为。因为标准明确规定:
Cv 限定引用格式错误,除非通过使用 typedef-name(7.1.3、14.1)或 decltype-specificer (7.1.6.2) 引入 cv 限定符, 在这种情况下 cv 限定符被忽略
这意味着const A aref = 3;实际上等价于:
//---v------------>no const here because it is ignored
int & aref = 3; //the actual problem is that a non-const lvalue reference cannot bind to rvalue
也就是说,实际的问题是“非常量左值引用不能绑定到右值”并且不是“我们正在将const 应用于引用”。
那么我的分析是否正确,而用户的说法不正确?
【问题讨论】:
-
相当于
int & aref = 3,你的分析是正确的。 -
您可以通过
static_assert(std::is_same_v<const A, int &>);确认您的分析。 -
@NathanOliver Ok