Default initialization of structs?

David Nadlinger via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 17 05:31:33 PDT 2016


On Friday, 17 June 2016 at 11:10:12 UTC, Gary Willoughby wrote:
> Thanks, I forgot to mention I'm also doing lots of other stuff 
> in the constructor to private fields too.
>
> struct Foo(T)
> {
>     private int _bar;
>     private void* _baz;
>
>     this(int bar = 8)
>     {
>         this._bar = bar;
>         this._baz = malloc(this._bar);
>     }
> }
>
> So I have to at least run a constructor.

Structs cannot have a default constructor; .init is required to 
be a valid state (unless you @disable default construction). This 
is a deliberate language restriction, although you can argue 
about its value.

What you can do as a workaround is to provide a public static 
factory method while disabling default construction.

  — David


More information about the Digitalmars-d-learn mailing list