Klaus
Klaus

Reputation: 25663

running into trouble with constexpr

I run into trouble while initializing a class with constants:

Why the initialisation with a pointer to a member in the same class results into an error? The error comes up without using the class "Use"!

class A
{   
    private:
        int a;
        const int* const aptr;

    public:
        constexpr A( int _a):
            a(_a)
           , aptr( &a)           // why aptr could not be initialized? 
    {}  
};  

class Data { } d1; 

class B
{   
    private:
        Data* dptr1;

    public:
        constexpr B(Data* _p): dptr1( _p) {}

};  

class Use 
{   
    static constexpr A a{2};   // fail! error: field initializer is not constant
    static constexpr B b{&d1}; // works
};  

Upvotes: 6

Views: 724

Answers (1)

Richard Smith
Richard Smith

Reputation: 14188

The code is valid, and Clang accepts it; this seems to be a g++ bug. The address of Use::a.a is an address constant expression, since it evaluates to the address of an object with static storage duration, so it can be used to initialize a constexpr object.

Upvotes: 3

Related Questions