【问题标题】:Is const A aref = 3 equivalent to int & const aref = 3 OR int & aref = 3const A aref = 3 是否等同于 int & const aref = 3 OR int & aref = 3
【发布时间】: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

标签: c++ reference constants


【解决方案1】:

您的分析是正确的,声明是不正确的,因为const A aref = 3; 相当于:

int & aref = 3;

这不起作用(正如您在问题中已经指出的那样),因为非 const 左值引用不能绑定到右值。

甚至可以确认这一点,如果您在 gcc 上尝试此操作,则会收到错误提示:

error: cannot bind non-const lvalue reference of type ‘A’ {aka ‘int&’} to an rvalue of type ‘int’

这确认它等同于int & aref = 3;

【讨论】:

    猜你喜欢
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    相关资源
    最近更新 更多