13

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Andrew Parker
  • 1,425
  • 2
  • 20
  • 28

1 Answers1

10

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.

m.s.
  • 16,063
  • 7
  • 53
  • 88
  • 2
    Great, thanks for that. I'm basically trying to assure that MSVC is incorrect in behaviour before I submit a bug. I was pleased to see constexpr was finally implemented in VS 2015, but it still doesn't work properly. Case 1 above fails in VS, even with 2015 [sigh]. +1 for the link as well. That's an awesome tool. Useful in conjunction with http://webcompiler.cloudapp.net/. – Andrew Parker Aug 11 '15 at 10:07
  • The page for LiteralType have been moved to https://en.cppreference.com/w/cpp/named_req/LiteralType – Hanif Bin Ariffin May 18 '20 at 21:55