Would love to override default ctor of struct

aliak something at something.com
Thu Feb 7 13:04:15 UTC 2019


On Thursday, 7 February 2019 at 11:14:47 UTC, Nick Treleaven 
wrote:
> On Thursday, 31 January 2019 at 15:41:28 UTC, Jonathan M Davis 
> wrote:
>> The main problem with allowing a constructor with no 
>> parameters when you @disable this(); is that it wouldn't act 
>> like a default constructor and really couldn't act like one in 
>> general, because too much is designed around using init. To
>
> I'm not asking for a default constructor, only an explicit 
> nullary argument ctor.
>
>> Also, it's perfectly possible to use a factory function to 
>> create immutable objects. Worst case, you have to cast to 
>> immutable in the factory function, but it works just fine.
>
> Have you changed your opinion? You said only that "in some 
> situations" casts can be used:
>
> "The only downside that I can think of at the moment for using 
> a factory function over having this() as a non-default 
> constructor is that when constructing immutable objects, the 
> constructor usually has to do it (though in some situations, 
> casts could be used - that depends primarily on whether the 
> data is guaranteed to be unique). So, such a factory function 
> would require a special constructor with dummy arguments or 
> something similar in order to construct immutable objects."
>
>> AFAIK, aside from stuff that requires that the type be 
>> default-initialized, the only thing that you can't really do 
>> with @disable this(); is to completely guarantee that all 
>> objects are constructed via the factory method, because the 
>> init value for the type still exists and can still be used. It 
>> just isn't used for default initialization. So, having a type 
>> with @disable this(); that does not take the init value into 
>> account can cause bugs.
>
> struct S
> {
>     static @disable S init;
>     ...
>
>> But all of the other stuff with regards to immutable and the 
>> like can still be done. It just can't necessarily be done in 
>> an @safe manner.
>
> This is a significant downside, you can't have a @safe struct 
> that requires runtime calls for its construction but no 
> arguments.

It seems to me that the only argument I've heard to not allow 
default construction is because people will get confused as to 
why array initialization doesn't use the constructor, and maybe 
some other cases. But, at the same time, the difference between 
construction and initialization is a said to be a "core concept" 
of D. So this seems quite reasonably solved with some 
documentation and just being more explicit about the separation 
between construction and initialization?

It certainly beat the (exaggerated) weekly forum posts asking for 
default struct construction and why it's not allowed (speaking of 
confusing people) :)

Cheers,
- Ali


More information about the Digitalmars-d mailing list