1

The answer to this question from @Vittorio Romeo explains constinit very well. In his answer, the following is mentioned:

constexpr is not equivalent to const constinit, as the former mandates constant destruction, while the latter doesn't.

Although pretty clear, I fail to see any practical use of this. In which case would const constinit be used, but constexpr could not. In any case that I can think of, for any type T that can be constinit and cannot be changed during runtime via const, constant destruction should be a trivial restriction to add. Am I missing something?

rawrex
  • 4,044
  • 2
  • 8
  • 24
Brotcrunsher
  • 1,964
  • 10
  • 32
  • 1
    If you have a type you cannot change and the destructor is not constexpr? I had a similar case the other day, fortunately I was in control of the destructor's code and could change it. – bitmask Jul 02 '21 at 11:23
  • @bitmask So the only case where this could be useful is if you can't change the type `T`? – Brotcrunsher Jul 02 '21 at 11:27
  • I mean, there could be a legitimate reason why the dtor is non-constexpr but the ctor is. I just cannot think of one. – bitmask Jul 02 '21 at 11:41
  • Maybe some constructors are constexpr, but other function/ctors cannot be (and are allocating resources), and the destructor must then be non-constexpr ? – Khoyo Jul 02 '21 at 11:48
  • @Brotcrunsher: Does there need to be a use case? Why add language to the standard to stop people from using a particular combination of qualifiers, just because some other qualifier might be better for them? – Nicol Bolas Jul 02 '21 at 13:29
  • @Nicol Bolas For the same reason why the `register` keyword was removed (still reserved though). For something to be a part of a language, I guess it should have some kind of use - this is obviously just my opinion though. If this would not be the case, then why wasn't the `fizzbuzz` keyword introduced long ago, which does absolutely nothing but can be placed where ever you want? – Brotcrunsher Jul 02 '21 at 13:35
  • @Brotcrunsher: No, `register` was *never* useful. `const` is useful. `constinit` is useful. And they're not the same *kind* of qualifier, so they're not automatically mutually exclusive. So you'd have to invent a reason to forbid their use *together*. – Nicol Bolas Jul 02 '21 at 13:42

2 Answers2

0

If you have a dependency on external code that you cannot change for whatever reason, and it looks like this

struct A {
  ~A() {}
};

This will mean that A is not a literal type because it doesn't have a constexpr destructor (most likely an oversight). It could however be constructed at compile time and therefore be a constinit.

bitmask
  • 32,434
  • 14
  • 99
  • 159
0

A possible practical case:

struct AtExit
{
    ~AtExit() { std::cout << "End"; }
};

Demo

(More useful by templating the class with functor).

Jarod42
  • 203,559
  • 14
  • 181
  • 302