constexpr 用指针初始化

2022-01-23 00:00:00 pointers constants c++ constexpr

我正在尝试使用指向 int 的指针初始化 constexpr 声明,该指针是一个 const 对象.我也尝试用非 const 类型的对象来定义对象.

I am trying to initialize a constexpr declaration with a pointer to int which is a const object. I also try to define an object with a object that is not a const type.

代码:

#include <iostream>

int main()
{
constexpr int *np = nullptr; // np is a constant to int that points to null;
int j = 0;
constexpr int i = 42; // type of i is const int
constexpr const int *p = &i; // p is a constant pointer to the const int i;
constexpr int *p1 = &j; // p1 is a constant pointer to the int j; 
}

g++ 日志:

constexpr.cc:8:27: error: ‘& i’ is not a constant expression
constexpr.cc:9:22: error: ‘& j’ is not a constant expression

我相信这是因为 main 中的对象没有固定地址,因此 g++ 正在向我抛出错误消息;我将如何纠正这个?不使用文字类型.

I believe it is because the objects in main have no fixed addresses, thus g++ is throwing error messages back at me; how would I correct this? Without using literal types.

推荐答案

让它们static来固定它们的地址:

Make them static to fix their addresses:

int main()
{
  constexpr int *np = nullptr; // np is a constant to int that points to null;
  static int j = 0;
  static constexpr int i = 42; // type of i is const int
  constexpr const int *p = &i; // p is a constant pointer to the const int i;
  constexpr int *p1 = &j; // p1 is a constant pointer to the int j; 
}

这被称为地址常量表达式 [5.19p3]:

This is known as an address constant expression [5.19p3]:

地址常量表达式是prvalue核心常量表达式指针类型,计算为静态对象的地址存储持续时间、函数地址或空指针value 或 std::nullptr_t 类型的纯右值核心常量表达式.

An address constant expression is a prvalue core constant expression of pointer type that evaluates to the address of an object with static storage duration, to the address of a function, or to a null pointer value, or a prvalue core constant expression of type std::nullptr_t.

相关文章