6

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
};  
3
  • @Morwenn: By the time aptr is being constructed, a has already been constructed and has a valid address. Commented May 14, 2013 at 9:36
  • I you initialize A and B outisde of Use with g++, you get sorry, unimplemented: use of the value of the object being constructed in a constant expression. Commented May 14, 2013 at 9:45
  • I think you either have a typo or UB here: You're taking the address of a function parameter, that doesn't exist any more after the ctor of A has finished. Maybe you want constexpr A(int& _a)? Commented May 14, 2013 at 11:09

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think you mean gcc.gnu.org/PR57694
Sorry, you are right. The bug report is gcc.gnu.org/bugzilla/show_bug.cgi?id=57694

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.