constexpr wird mit Zeigern initialisiert

Ich versuche, eine constexpr-Deklaration mit einem Zeiger auf int zu initialisieren, bei dem es sich um ein const-Objekt handelt. Ich versuche auch, ein Objekt mit einem Objekt zu definieren, das kein const-Typ ist.

Code:

#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 ++ log:

constexpr.cc:8:27: error: ‘& i’ is not a constant expression
constexpr.cc:9:22: error: ‘& j’ is not a constant expression

Ich glaube, das liegt daran, dass die Objekte in main keine festen Adressen haben. Daher wirft g ++ Fehlermeldungen auf mich zurück. Wie würde ich das korrigieren? Ohne Verwendung von Literalen.

Antworten auf die Frage(1)

Ihre Antwort auf die Frage