我在用常量初始化类时遇到了麻烦:
为什么使用指向同一类中成员的指针进行初始化会导致错误? 没有使用“使用”类就出现了错误!
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/