遇到麻烦了

running into trouble with constexpr

本文关键字:麻烦 遇到      更新时间:2023-10-16

我在用常量初始化类时遇到了麻烦:

为什么使用指向同一类成员的指针初始化会导致错误?错误出现没有使用类"使用"!

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
};  

代码是有效的,Clang接受它;这似乎是一个c++ bug。Use::a.a的地址是一个地址常量表达式,因为它的计算结果是一个具有静态存储持续时间的对象的地址,所以它可以用来初始化constexpr对象。