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
};
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With