C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Expanding constinit

From: Jan Schultke <janschultke_at_[hidden]>
Date: Fri, 26 Jan 2024 12:03:03 +0100
> The constinit would (at least potentially) happen during compile-time instead?

You seem to misunderstand something here. This is impossible.

Even constexpr merely implies that the initializer can be evaluated at
compile-time. However, the initialized object is always a new object,
which is initialized at run-time. For example, if we write:

> constexpr int x = 10 + 5;

This guarantees that the evaluation of the initializer 10 + 5 can take
place at compile-time. However, each time the surrounding function is
called, a new object x with value 15 is initialized, at run-time.

With that in mind, I don't see any reason why constinit shouldn't be
permitted for variables with automatic storage duration. It could
simply mean "constexpr, but the object is mutable once initialized".

Consider the following motivating example:
> constinit config c{ .buffer_size = compute_size(...) };
> c.host_name = get_host_name_from_os();
> start_service(c);

In this example, portions of c are computed at compile-time, and other
portions are added later at run-time.

Received on 2024-01-26 11:03:15