c++ - const A aref = 3 等于 int & const aref = 3 OR int & aref = 3

标签 c++ reference constants typedef

我正在使用列出的资源学习 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

Demo

这证实它相当于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/

相关文章:

c - 将字符数组打字为 const char *

c++ - 与 const 和指针相关的问题

c++ 等效于 calloc 并为数组变量声明空间

arrays - awk 问题(从用户定义的函数返回一个数组)

java - 我正在java中实现链表,但我的代码既没有给出任何错误,也没有产生任何输出

php - 通过 __get() 通过引用返回 null

c - 删除 C 结构中指针的常量性

c++ - 如何将 warn() 的输出转换为字符串?

c++ - %F 不返回任何输出

c++ - 使用类属性调用具有非类型模板参数的模板函数