【发布时间】:2021-05-25 22:16:46
【问题描述】:
关于 constexpr 表达式的问题有很多问题/答案,但我有一个问题与其他问题非常接近,但在另一种意义上略有不同。反正就是这样。
#include <iostream>
using namespace std;
constexpr int x = 1; // TAG A
int main() {
constexpr int &xf = x; // TAG B error out
const int &xf1 = x; // TAG C works
constexpr int const &xf2 = x; // TAG D works
return 0;
}
错误:
Binding reference of type 'int' to value of type 'const int' drops 'const' qualifier [reference_bind_drops_quals]
评论:
- 标签 A 清楚地表明 x 是 const int。根据 C++ Primer 第 5 版第 2.44 页“变量 声明为 constexpr 是隐式 const 并且必须由常量初始化 表达式:“。所以这很好。
- TAG B --> 错误消息暗示 constexpr 没有隐含地“const”变量 xf。因此 xf 是 int &。这与 TAG A 相矛盾。为什么?
- TAG C --> 这是对 const 的常用引用
- TAG D --> 由于它在 TAG B 中的行为方式,添加了额外的“const”以使其成为 const 引用。
“对 const 的引用”和“const 引用”这两个词有区别吗?
似乎对 const 的引用意味着引用是指一个 const 对象,但不允许进行修改,而“const 引用”是指引用是 const 但它可以指向 const 或非 const 对象。
这是一件令人困惑的大事。
【问题讨论】: