Why can't a destructor be marked constexpr?

Viewed 7097

In C++, you can declare many things as constexpr: variables, functions (including member functions and operators), constructors, and since C++1z, also if statements and lambda expressions. However, declaring a destructor constexpr results in an error:

struct X {
    constexpr ~X() = default; // error: a destructor cannot be 'constexpr'
};

My questions:

  1. Why can't a destructor be marked constexpr?
  2. If I do not provide a destructor, is the implicitly generated destructor constexpr?
  3. If I declare a defaulted destructor (~X() = default;), is it automatically constexpr?
6 Answers

Since C++20, a constructor may be marked constexpr; I don’t know if it says anywhere specifically “a destructor may be constexpr”, but the draft standard includes the following text in section 9.2.5 paragraph 5:

The definition of a constexpr destructor whose function-body is not = delete shall additionally satisfy the following requirement:

  • for every subobject of class type or (possibly multi-dimensional) array thereof, that class type shall have a constexpr destructor.

This also now has a useful function because C++20 also allows new and delete in constexpr contexts, allowing things like vector and string to work at compile time without hacks (although I believe C++20 does not actually include changes to the standard library to allow for this, it is possible to implement something with the same API and behaviour as vector that works completely at compile time).

Related