关于c ++:如何初始化constexpr引用

how to initialize a constexpr reference

我试图初始化一个constexpr引用,但没有成功。我试过

1
2
3
4
5
6
7
8
9
10
11
12
#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
}

但我有一个编译时错误

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

丢弃const会导致

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

尽管我觉得constexpr自动暗示const用于变量声明。

所以我的问题是:

  • constexpr引用是否有用?(即,"优于"const参考文献)
  • 如果是,我如何有效地定义它们?
  • PS:我已经看到了一些与我相关的问题,例如哪些值可以分配给"constexpr"引用?但我认为他们没有回答我的问题。


  • Are constexpr references ever useful? (i.e.,"better" than const references)
  • 它们保证在程序启动之前被初始化,而对const的引用可以在程序启动运行之后的动态初始化期间初始化。

  • If yes, how can I effectively define them?
  • constexpr引用必须绑定到全局变量,而不是局部变量(或者更正式地说,它必须绑定到具有静态存储持续时间的对象)。

    在概念上,引用等价于获取变量的地址,并且局部变量的地址不是常量(即使在main中,也不能调用一次,因此其局部变量只能初始化一次)。


    所以问题在于,一个COSTEXPR引用需要绑定到一个静态存储持续时间的对象,该对象覆盖在C++ 11标准草案中:N33 37节EDOCX1×2〔Exp.const〕(强调雷):

    A reference constant expression is an lvalue
    core constant expression that designates an object with static storage duration or a function

    C++ 14标准草案:N39 36改变措辞:

    A constant expression is either a glvalue core constant expression whose value refers to an object with static
    storage duration or to a function, or a prvalue core constant expression whose value is an object where, for
    that object and its subobjects:

    • each non-static data member of reference type refers to an object with static storage duration or to a
      function, and
    • if the object or subobject is of pointer type, it contains the address of an object with static storage
      duration, the address past the end of such an object (5.7), the address of a function, or a null pointer
      value.

    因此,像这样更改x的声明将起作用:

    1
    constexpr static int x{20};


    正如T.C.所说,初始值设定项需要是具有静态存储持续时间的对象。

    N4140/§5.19/4 A constant expression is either a glvalue core
    constant expression whose value refers to an object with static
    storage duration [...]

    N4140/§7.1.5/9 A constexpr specifier used in an object declaration
    declares the object as const. Such an object shall have literal type
    and shall be initialized. [...] Otherwise, or if a constexpr
    specifier is used in a reference declaration, every full-expression
    that appears in its initializer shall be a constant expression.

    在N3337中,措辞不同。