如何初始化 constexpr 引用
我试图初始化一个 constexpr
引用,但没有成功.我试过了
#include constexpr int&f(int& x)//可以定义返回 constexpr 引用的函数{返回 x;}int main(){constexpr int x{20};constexpr const int&z = x;//此处出错}
但我收到编译时错误
<块引用>错误:constexpr 变量 'z' 必须由常量表达式初始化
删除 const
导致
错误:将int"类型的引用绑定到const int"类型的值会丢弃限定符
尽管我感觉 constexpr
自动暗示了变量声明的 const
.
所以我的问题是:
constexpr
引用有用吗?(即,比const
引用更好")- 如果是,我如何有效地定义它们?
PS:我看到了一些与我的相关的问题,例如 哪些值可以分配给 `constexpr` 引用? ,但我认为他们没有解决我的问题.
解决方案
- constexpr 引用有用吗?(即,比 const 引用更好")
它们保证在程序启动之前被初始化,而对 const 的引用可以在程序开始运行后的动态初始化期间初始化.
<块引用>- 如果是,我如何有效地定义它们?
constexpr
引用必须绑定到全局变量,而不是局部变量(或者更正式地说,它必须绑定到具有静态存储持续时间的东西).
引用在概念上等同于获取变量的地址,而局部变量的地址不是常量(即使在只能调用一次的main
中,因此它的局部变量是只初始化一次).
I am trying to initialize a constexpr
reference with no success. I tried
#include <iostream>
constexpr int& f(int& x) // can define functions returning constexpr references
{
return x;
}
int main()
{
constexpr int x{20};
constexpr const int& z = x; // error here
}
but I'm getting a compile time error
error: constexpr variable 'z' must be initialized by a constant expression
Dropping the const
results in
error: binding of reference to type 'int' to a value of type 'const int' drops qualifiers
even though I had the feeling that constexpr
automatically implies const
for variable declarations.
So my questions are:
- Are
constexpr
references ever useful? (i.e., "better" thanconst
references) - If yes, how can I effectively define them?
PS: I've seen a couple of questions related to mine, such as Which values can be assigned to a `constexpr` reference? , but I don't think they address my questions.
解决方案
- Are constexpr references ever useful? (i.e., "better" than const references)
They are guaranteed to be initiailized before the program starts, whereas a reference to const can be initialized during dynamic initialization, after the program starts running.
- If yes, how can I effectively define them?
A constexpr
reference has to bind to a global, not a local variable (or more formally, it has to bind to something with static storage duration).
A reference is conceptually equivalent to taking the address of the variable, and the address of a local variable is not a constant (even in main
which can only be called once and so its local variables are only initialized once).
相关文章