8.3.2/1:
Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name (7.1.3, 14.1) or decltype-specificer (7.1.6.2), in which case the cv-qualifiers are ignored
int a = 5;
const int &b = a;
int main()
{
}
gcc
和 clang
都能很好地编译。 DEMO
为什么?是错误吗?
示例,由标准提供:
typedef int& A;
const A aref = 3; // ill-formed; lvalue reference to non-const initialized with rvalue
最佳答案
在您的示例中,您没有 cv 限定的引用。标准的引用是指以下格式错误的声明
int a = 5;
const int & const b = a;
这里的 b 是一个 cv 限定的引用,代码片段的格式不正确。
至于您的代码片段,它声明了对 const 对象的引用。
此代码片段格式错误
typedef int& A;
const A aref = 3;
因为它等同于
int & const aref = 3;
比较两个声明会更清楚
int x;
int * const p = &x;
int & const r = x;
cv 限定指针的声明有效,而 cv 限定引用的声明格式错误。
关于c++ - 简历合格的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26083067/