Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
};  
like image 907
Klaus Avatar asked May 14 '13 09:05

Klaus


People also ask

What is the point of constexpr?

constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.

Is constexpr faster?

Not only will your code be faster and smaller, it'll be safer. Code marked constexpr can't bitrot as easily. constexpr-everything is still a prototype – it has a couple of rough edges left.

Does constexpr imply const?

The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time. Such variables and functions can then be used where only compile time constant expressions are allowed. constexpr implies const.


1 Answers

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.

like image 91
Richard Smith Avatar answered Oct 17 '22 16:10

Richard Smith