Initializing the value of the POD structure is constexpr?

Consider the structure:

struct mystruct { }; 

Is it true that this is always true:

 constexpr mystruct mystructInstance = mystruct(); 

i.e. what initialization of the POD value is equal to constexpr ? Similarly, how to determine if a structure is defined:

 struct mystruct { ~mystruct(); }; 

Finally, how about this:

 struct mystruct { mystruct(); ~mystruct(); }; 

I did not declare ctr as constexpr, however, are there any implicit deduction rules that guarantee this?

+4
source share
1 answer

Requirements for constexpr variables:

The constexpr variable must satisfy the following requirements:

  • its type must be LiteralType.
  • it must be immediately created or assigned a value.
  • constructor parameters or assigned value should contain only literals, constant variables and functions.
  • the constructor used to construct the object (implicit or explicit) must satisfy the requirements of the constexpr constructor. In the case of an explicit constructor, it must have constexpr.

Given your 3 structures:

 struct mystruct_1 { }; struct mystruct_2 { ~mystruct_2(); }; struct mystruct_3 { mystruct_3(); ~mystruct_3(); }; 

mystruct_1 is LiteralType . So, the following is true and compiled:

 constexpr mystruct_1 mystructInstance_1 = mystruct_1(); 

mystruct_2 not a LiteralType , since it has a nontrivial destructor. Therefore, the following is not valid and will not compile:

 constexpr mystruct_2 mystructInstance_2 = mystruct_2(); 

The same applies to mystruct_3 , moreover, it is not aggregate and does not provide a constexpr constructor. Therefore, the following is not valid and will not compile:

 constexpr mystruct_3 mystructInstance_3 = mystruct_3(); 

You can also view descriptive error messages in this online demo .

+3
source

All Articles