我有以下代码
constexpr int into(int a,int b)
{
int c=a*b;
return c;
}
int main()
{
constexpr int &n=into(5,5);
}
并且我已经阅读(在 MSDN 中)
The keyword
constexpr
was introduced in C++11 and improved in C++14. It means constant expression. Likeconst
, it can be applied to variables so that a compiler error will be raised if any code attempts to modify the value.
看完之后,我以为constexpr
可以用来代替const
,但是对于上面的代码,我得到一个编译器错误说明
`int main()': invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'`
当 constexpr
被替换为 const
时,它工作正常。我不明白这种行为;有人可以解释一下吗?
最佳答案
不同于const
, 适用于 int
, constexpr
关键字将 const 直接应用于引用类型的变量 int&
, 无效。
typedef int &int_ref;
int main() {
int x = 1;
int &a = x; // OK
int_ref b = x; // OK, int_ref is 'int &'
const int &c = 1; // OK, reference to const int
const int_ref d = 1; // error: type of d is 'int &'
// qualifier on reference are being ignored
}
constexpr int &n
和 constexpr int_ref n
是一样的,
同时 const int &n
和 const int_ref n
有不同的限定词。
关于c++ - 为什么右值不能分配给 constexpr 引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37003573/