In which practical case is "const constinit" useful?

195 views Asked by At

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?

2

There are 2 answers

0
bitmask On

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.

0
Jarod42 On

A possible practical case:

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

Demo

(More useful by templating the class with functor).