struct: default construction or lazy initialization.
kinke via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Feb 1 15:41:39 PST 2017
On Wednesday, 1 February 2017 at 23:32:12 UTC, bitwise wrote:
> On Wednesday, 1 February 2017 at 23:24:27 UTC, kinke wrote:
>> It's not that bad. D just doesn't support a default ctor for
>> structs at all and simply initializes each instance with
>> T.init. Your `s2` initialization is most likely seen as
>> explicit default initialization (again with T.init).
>> Destructing both instances is exactly what should happen.
>
>
> I was going to add a point about this.
>
> 1| S s1;
> 2| S s2 = S();
>
> The effect of line 1 and 2 are exactly the same - which is that
> the lhs ends up with S.init. S.this() should either be called
> at line 2, or the syntax of line 2 should be forbidden on the
> grounds that default struct ctors cannot be declared.
Yep, they are the same. Initialization with S.init is a trivial
blit from a compile-time constant, so there's no call to a
default ctor. This in turn makes construction of static arrays
and structs containing a field of type S trivial, as no default
ctor has to be generated if a field has one, there are no
potential exceptions etc.
Ideally, S.this() would be called in both cases (just like C++).
The explicit syntax in line 2 is useful for stuff like `const s =
S();`.
More information about the Digitalmars-d-learn
mailing list