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 .
source share