const A aref = 3 相当于 int & const aref = 3 或 int & aref = 3



我正在使用此处列出的资源学习C++。我遇到了以下我认为不正确的说法:

typedef int& A;
const A aref = 3; 

因为它相当于

int & const aref = 3; 

正如您在上面的代码片段中看到的,用户声称const A aref等价于int & const aref。现在,我的问题是上述声明在技术上正确吗?

我不这么认为。因为标准特别规定:

Cv限定引用格式错误,除非通过使用typedef名称(7.1.3,14.1(或decltype specifier(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

也就是说,实际的问题是;非常量左值引用不能绑定到右值";并且不是";我们已经将CCD_ 4应用于参考文献";。

那么,我的分析是否正确,用户的说法是否不正确?

您的分析是正确的,索赔是不正确的,因为const A aref = 3;等效于:

int & aref = 3;

这将不起作用(正如您在问题中已经指出的(,因为非常量的左值引用无法绑定到右值。

甚至可以使用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’

最新更新