我有以下简单代码:
constexpr int x = 1;
constexpr int &y = x; -- error. qualifiers dropped in binding reference of type "int &" to intializer of type "const int"
问题:
为什么引用 y 不是 const int & ?根据 C++ Primer 第 5 版第 2.4.4 节(constexpr 变量),所有 constexpr 变量都是隐式 const。
谢谢。
const int &
不是“对 int 的 const 引用”。这是“对 const int 的引用”。
与指针不同,引用永远不能是
const
。尽管无法修改它们以指向不同的对象,但它们永远不会被视为const
。
constexpr
仅在顶层添加常量。例如,constexpr int *x
创建类型为 int *const
(指向 int 的 const 指针)的变量,而不是 const int *
(指向 const int 的指针)。
由于引用不能是 const,因此
constexpr
隐含的常量性将被忽略,结果类型只是 int &
。