Consider the struct:
struct mystruct { };
Is it true that this is always valid:
constexpr mystruct mystructInstance = mystruct();
i.e. that value initialization of POD is a constexpr
? Similarly how about if the struct is defined to be:
struct mystruct { ~mystruct(); };
Finally, what about this:
struct mystruct { mystruct(); ~mystruct(); };
I haven't declared the ctr as constexpr, however are there any implicit deduction rules which guaratee this?
The requirements for constexpr
variables are:
A constexpr variable must satisfy the following requirements:
- its type must be a LiteralType.
- it must be immediately constructed or assigned a value.
- the constructor parameters or the value to be assigned must contain only literal values, constexpr variables and functions.
- the constructor used to construct the object (either implicit or explicit) must satisfy the requirements of constexpr constructor. In the case of explicit constructor, it must have constexpr specified.
Given your 3 structs:
struct mystruct_1 { };
struct mystruct_2 { ~mystruct_2(); };
struct mystruct_3 { mystruct_3(); ~mystruct_3(); };
mystruct_1
is a LiteralType
. So the following is valid and compiles:
constexpr mystruct_1 mystructInstance_1 = mystruct_1();
mystruct_2
is not a LiteralType
since it has a non-trivial destructor.
Therefore the following is invalid and fails to compile:
constexpr mystruct_2 mystructInstance_2 = mystruct_2();
The same applies for mystruct_3
, additionally it is not an aggregate and does not provide a constexpr
constructor.
So the following is also invalid and fails to compile:
constexpr mystruct_3 mystructInstance_3 = mystruct_3();
You can also have a look at the descriptive error messages in this online demo.
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