Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value initialization of POD struct is a constexpr?

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?

like image 406
Andrew Parker Avatar asked Aug 11 '15 09:08

Andrew Parker


1 Answers

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.

like image 184
m.s. Avatar answered Sep 19 '22 13:09

m.s.