[英]constexpr initializing with pointers
我正在尝试使用指向作为const对象的int的指针来初始化constexpr声明。 我还尝试使用非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 ++向我抛出了错误消息; 我该如何纠正? 不使用文字类型。
使它们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]:
地址常量表达式是指针类型的prvalue核心常量表达式,其值为静态存储持续时间的对象的地址,函数的地址或空指针值,或者为std类型的prvalue核心常量表达式: :nullptr_t。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.