C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Expanding constinit

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Fri, 26 Jan 2024 15:12:00 +0300
On 1/26/24 14:43, Jan Schultke via Std-Proposals wrote:
>> So the object is mutable and the (first?) initialization (construction) happens during compile-time?
>
> No, the initialization takes place at run-time. You probably
> understand it conceptually but you're not putting it into the right
> words. The evaluation of the initializer may take place at
> compile-time, but the initialization takes place at run-time, both for
> constexpr and constinit. Even static constexpr objects are initialized
> at run-time; namely when the program starts and their object
> representation is loaded from the executable. There is no such thing
> as "initialized at compile-time". This would imply that the object
> exists outside of time and space, for all eternity, on all machines,
> once you compile.

Constant initialization basically means whatever underlying
representation of an initialized object is generated at compile time and
saved in a read-only data section of the executable. Upon loading the
executable, the representation of the object is also mapped into the
process address space, so really no initialization happens at run time
(as in, while the program is running - neither during the
namespace-scope dynamic initialization stage nor during main()).

A variable declared constexpr specifies to create a compile-time
constant which can be used in other constant expressions. That's the
primary intent of constexpr - to be able to participate in constant
expressions. The fact that it also allows for such constants to be
initialized at compile-time, (i.e. during constant initialization, as
described above) in some cases is a byproduct of that.

constinit has a different intention. It explicitly requires that
initialization happens during compile time, i.e. at constant
initialization stage. This is not possible to do for automatic variables
because automatic storage cannot be initialized at compile time.

Received on 2024-01-26 12:12:04