What's the real difference between "constinit" and "constexpr"? [duplicate]
Asked Answered
F

1

7
constexpr int f() { return 0; }
int g() { return 0; }

constexpr auto c1 = f(); // OK
constinit auto c2 = f(); // OK

constexpr auto d1 = g(); // ill-formed
constinit auto d2 = g(); // ill-formed

int main() {}

As illustrated in the code above, I cannot find any difference between constinit and constexpr.

What's the real difference between constinit and constexpr?


Update:

The related What is constinit in C++20? doesn't clearly state the difference between constinit and constexpr.

Frail answered 18/6, 2020 at 7:22 Comment(2)
@E_net4thedupefinder, the answer in your link doesn't clearly state the difference between constinit and constexpr.Frail
Yes, it does. The very first answer goes into explicit detail about what constexpr entails and how constinit does not imply most of those things.Earthlight
P
8

A constinit variable is constant initialized, but it is not usable in a constant expression, nor even automatically constant. Your main can legally contain this line

c2 = 2; 

Yup, modification is possible after initialization.

Pallette answered 18/6, 2020 at 7:27 Comment(2)
From cppreference: "constexpr mandates that the object must have static initialization and constant destruction and makes the object const-qualified, however, constinit does not mandate constant destruction and const-qualification." Just for me, can you just hint me what does this constant destruction means; just how constexpr mandates this and constinit is not.Teamwork
@AccessDenied - I can't. As far as I can tell this is something that appears only on cppreference, and so may very well be cooked up by whomever edited that entry.Pallette

© 2022 - 2024 — McMap. All rights reserved.