The*_*Cat 11 c++ pointers const constexpr
我试图用指向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;
}
Run Code Online (Sandbox Code Playgroud)
g ++日志:
constexpr.cc:8:27: error: ‘& i’ is not a constant expression
constexpr.cc:9:22: error: ‘& j’ is not a constant expression
Run Code Online (Sandbox Code Playgroud)
我相信这是因为main中的对象没有固定的地址,因此g ++会向我发送错误消息; 我该怎么纠正这个?不使用文字类型.
Jes*_*ood 14
让他们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;
}
Run Code Online (Sandbox Code Playgroud)
这称为地址常量表达式 [5.19p3]:
地址常量表达式是指针类型的prvalue核心常量表达式,其计算为具有静态存储持续时间的对象的地址,函数的地址,或空指针值,或std类型的prvalue核心常量表达式: :nullptr_t.