c++ - 使用 constexpr 遇到麻烦

标签 c++ c++11 constexpr

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

为什么使用指向同一类中成员的指针进行初始化会导致错误? 没有使用“使用”类就出现了错误!

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接受;这似乎是一个 g++ 错误。 Use::a.a 的地址是一个地址常量表达式,因为它的计算结果是一个具有静态存储持续时间的对象的地址,所以它可以用来初始化一个constexpr对象。

关于c++ - 使用 constexpr 遇到麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16539649/

相关文章:

c++ - 给定键,如何找到 BST 的某个元素?

c++ - 有没有办法在 QDomDocument 中执行 javascript?

c++ - 制作不存储 value_type 的 InputIterator

C++11,GCC 4.8.1,Code::Blocks,线程,好头疼

c++ - 在 C++ 中检查字符串变量的 cin.fail() 时出错

C++11:unordered_map/set 是否保证遍历顺序为插入顺序?

c++ - 标准 vector 之上的 C++11 包装器类

c++ - 字符串文字可以在常量表达式中下标吗?

c++ - "return-by-reference"或 "pass-by-reference"参数何时与 constexpr 兼容?

c++ - 根据某些条件在编译时生成字符串