Allow this() { } for structs

Q. Schroll at
Sat Nov 7 01:39:30 UTC 2020

On Friday, 6 November 2020 at 17:14:27 UTC, IGotD- wrote:
> On Friday, 6 November 2020 at 16:53:32 UTC, Q. Schroll wrote:
>> If T's this() isn't pure, T.init cannot exist.
> Why must T.init and this() be the same thing?

The more I think about T.init the more stupid I tend to find it. 
The best example is

     struct S
         Object obj = new Object();

not working as most people expect. There's *one* Object 
allocated, that S.init.obj refers to, and that one Object's 
reference is blitted into every constructed S. One way to get 
different immutable(S) with their own distinct obj is a pure S 
factory returning unique S so that it can be implicitly typed 
immutable; that factory can be static opCall. This is stupid; one 
shouldn't need factories for that. (Factories have their use 
cases, though.) The only other option is an immutable constructor 
(or a constructor suitable for constructing immutable), but since 
being a constructor, it needs a parameter. This is stupid; one 
shouldn't need to add useless parameters to any function, except 
maybe for compatibility with an interface. This isn't near that.

They need not necessarily. I find, it would add unnecessary 
confusion if T.init isn't derived from a this() call. That way, 
at least it is guaranteed that T.init has T's invariants met at 
least locally. (Locally meaning that looking at the object 
isolated, no invariant violation can be derived.) An example for 
a "global" invariant is "no two objects of that type have the 
same id", something that clearly cannot be verified nor refuted 
looking at objects individually.

More information about the Digitalmars-d mailing list