我正在使用列出的资源学习 C++ here 。我遇到了以下claim 我认为这是不正确的:
typedef int& A; const A aref = 3;
because it is equivalent to
int & const aref = 3;
正如您在上面的代码片段中看到的,用户声称 const A aref
等同于 int & const aref
。现在,我的问题是上述说法在技术上是否正确?
我不这么认为。因为标准明确指出:
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
这意味着 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
也就是说,实际的问题是“非常量左值引用无法绑定(bind)到右值”并且不是“我们正在将const
应用于引用”。
那么我的分析是否正确,而用户的说法是否不正确?
最佳答案
您的分析是正确的,而声明是不正确的,因为 const A aref = 3;
相当于:
int & aref = 3;
这不起作用(正如您在问题中已经指出的那样),因为非常量左值引用无法绑定(bind)到右值。
您甚至可以使用static_assert
确认这一点,如下所示:
static_assert(std::is_same_v<const A, int &>); //passes
这证实它相当于int & aref = 3;
。
或者甚至只是在 gcc 中尝试代码,您会收到错误消息:
error: cannot bind non-const lvalue reference of type ‘A {aka int&}’ to an rvalue of type ‘int’
关于c++ - const A aref = 3 等于 int & const aref = 3 OR int & aref = 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73155269/