如何初始化一个constexpr引用 [英] how to initialize a constexpr reference

查看:149
本文介绍了如何初始化一个constexpr引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图初始化一个 constexpr 引用没有成功。我尝试了

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


错误:constexpr变量'z'必须通过常量表达式初始化

error: constexpr variable 'z' must be initialized by a constant expression

删除 const 会导致


错误:binding引用类型'int'到类型为'const int'的下降限定符

error: binding of reference to type 'int' to a value of type 'const int' drops qualifiers

,尽管我感觉 constexpr 自动暗示变量声明的 const

even though I had the feeling that constexpr automatically implies const for variable declarations.


  1. constexpr 引用是否有用? ( const 引用)

  2. 如果是,我如何有效地定义它们?

  1. Are constexpr references ever useful? (i.e., "better" than const references)
  2. If yes, how can I effectively define them?



PS:我已经看过一些与我相关的问题,例如哪些值可以分配给`constexpr`引用?,但我不认为它们解决了我的问题。

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.

推荐答案



  1. constexpr引用是否有用? (即比const引用更好)


它们保证在程序之前启动

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.


    $ b $开始,而在动态初始化期间可以初始化对const的引用。 b
  1. 如果是,我如何有效地定义它们?

  1. If yes, how can I effectively define them?


A constexpr 引用必须绑定到全局,而不是局部变量(或更正式地,它必须绑定到具有静态存储持续时间的东西)。

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).

引用在概念上等同于获取变量的地址,并且局部变量的地址不是常量(即使在 main 中,它只能被调用一次,所以它的局部变量只被初始化一次)。

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).

这篇关于如何初始化一个constexpr引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆