constexpr 用指针初始化

问题描述 投票:0回答:2

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

代码:

#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++ 向我抛出错误消息;我该如何纠正这个问题?不使用文字类型。

c++ pointers constants constexpr
2个回答
22
投票

让他们

static
修复他们的地址:

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]:

地址常量表达式是纯右值核心常量表达式 指针类型,计算结果为具有 static 的对象的地址 存储持续时间、函数地址或空指针 值,或 std::nullptr_t 类型的纯右值核心常量表达式。


0
投票
#include <iostream>
// define i/j outside the function body, as mentioned in the book "c++ primer"
int j = 0;
constexpr int i = 42; // type of i is const int
int main()
{
   constexpr int *np = nullptr; // np is a constant to int that points to null;
   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; 
}
© www.soinside.com 2019 - 2024. All rights reserved.