std.format and uninitialized elements in CTFE

kinke noone at
Thu Dec 5 21:50:39 UTC 2019

On Thursday, 5 December 2019 at 20:47:02 UTC, Steven 
Schveighoffer wrote:
> Well, as long as all members are void initialized, then it 
> should have an effect right? I know that the compiler blits the 
> whole struct at once, but if it's all void initialized, it 
> doesn't have to.

LDC and DMD still pre-initialize it (optimizer disabled) in that 
case (and druntime etc. via generic `= T.init` code). I doubt 
there's a good use case for a struct defining all of its fields 
as uninitialized, without being able to be sensibly 
default-constructed (no default ctor). These cases are probably 
better handled outside the struct, i.e., where the dangerous 
uninitialized allocation resides, and can be handled in some 
little factory function returning a void-initialized stack 

E.g., this attempt at manually eliminating the init blit/memset 
before the ctor call:

struct S {
     int[32] data = void;
     bool isDirty = void;
     this() @disable;
     this(const int[] data) {[] = data[];
         isDirty = false;

can be expressed (and actually works) like this, maintaining 
sensible default-constructability at the price of a somewhat more 
verbose `S.get()` for manually optimized construction:

struct S {
     int[32] data;
     bool isDirty;
     static S get(const int[] data) {
         S r = void;[] = data[];
         r.isDirty = false;
         return r;

More information about the Digitalmars-d mailing list