用指针初始化的constexpr [英] constexpr initializing with pointers
问题描述
我正在尝试使用指向作为const对象的int的指针来初始化constexpr声明.我还尝试使用非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核心常量表达式 指针类型的值,该值的值是静态对象的地址 存储持续时间,函数地址或空指针 值,或类型为std :: nullptr_t的prvalue核心常量表达式.
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.
这篇关于用指针初始化的constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!