C++ 使用指针初始化constexpr

C++ 使用指针初始化constexpr,c++,pointers,constants,constexpr,C++,Pointers,Constants,Constexpr,我试图用指向int的指针初始化constexpr声明,int是一个const对象。我还尝试使用非常量类型的对象定义对象 代码: 我相信这是因为main中的对象没有固定地址,因此g++向我抛出错误消息;我该如何纠正这一点?不使用文字类型。使其静态以修复其地址: int main() { constexpr int *np = nullptr; // np is a constant to int that points to null; static int j = 0; static

我试图用指向int的指针初始化constexpr声明,int是一个const对象。我还尝试使用非常量类型的对象定义对象

代码:


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

使其
静态
以修复其地址:

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::nullptr\t类型的prvalue核心常量表达式


嗯,是的。变量只有在运行时分配一个地址时才有地址。@克里斯:是。如何定义一个函数,使其对象具有固定地址?我可以把函数声明为constexpr吗?@chris你能解释一下你的观点吗?constexpr的全部要点是,它是在compiletime定义的,主要使用文本类型(它们是预期类型)。我的观点是,函数中的对象具有分配给它们的临时地址(出于明显的原因)。这里,g++向我抛出了由于这些临时内存地址引起的错误消息。我怎么能声明一个不会执行此操作的函数(即,允许在控制流期间固定所有对象)。我非常怀疑您是否能够将地址或变量指针与
constexpr
关联起来。不幸的是,此示例在VS 2015中运行良好。可怜的Microsoft。静态变量的地址不是在链接时定义的,不是在编译时定义的吗?@anton_rh:是的,地址是在链接时确定的。不过,这与我上面的回答并不矛盾。@JesseGood我认为这是一个很好的阐述点。
constexpr
可以是编译后解析的值。
constexpr.cc:8:27: error: ‘& i’ is not a constant expression
constexpr.cc:9:22: error: ‘& j’ is not a constant expression
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; 
}