C++ Logo


Advanced search

[std-proposals] Declare as constinit, define as constexpr?

From: Greg Falcon <gfalcon_at_[hidden]>
Date: Tue, 12 Dec 2023 14:17:37 -0500
I looked around but didn't find any DRs addressing this issue.

P1143R2 allows `constinit` on declarations, not just definitions, because
`constinit` in a header declaration guarantees no initialization order
fiasco on that variable. Meanwhile, the stronger `constexpr` on a variable
definition provides lifetime protection during shutdown as well, since such
a variable must be trivially destructible.

The combination of the above suggests the following pattern:

// foo.hpp
extern constinit const int kFoo;

// foo.cpp
constexpr int kFoo = 1;

However, by the text of P1143R2 and the spec, this is not allowed; a
variable declared `constinit` anywhere must use `constinit` at the

Implementations have diverged on how to handle this. MSVC treats the above
as an error, clang emits a warning, and gcc silently accepts it. (

The `constexpr` requirements imply `constinit` (since they are strictly
stronger), but the core language does not allow this substitution in a
definition. Nor can an author write `constexpr constinit kFoo = 1;` in the
.cpp file to get the best of both worlds, as this is explicitly forbidden
as well.

If folks here think this topic is ripe for consideration, I will happily
file a core language issue.

Greg Falcon

Received on 2023-12-12 19:17:51