Default struct constructor

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Jan 31 13:57:41 UTC 2019


On Wednesday, January 30, 2019 5:29:46 AM MST Victor Porton via Digitalmars-
d wrote:
> Why the language specification disables default constructors for
> structs?
>
> It can be easily worked around:
>
> ---
> struct Dummy { }
>
> struct C {
>      this(Dummy dummy) { }
> }
> ---
>
> But this workaround (using Dummy) is silly.
>
> Isn't it better to allow default constructor and call it for both
> of the following?
>
> C x;
> C y = C();

One of the core concepts in D is that all types have a default value which
is known at compile time, and a number of places in the language rely on
that fact (e.g. the way that arrays are initialized depends on blitting the
init value of the type into the array). Because structs live directly
wherever they're placed rather than requiring references like classes do,
default construction for structs wouldn't play well with the semantics of
the language. It wouldn't necessarily be impossible to have it, but the
language was designed around default initialization and not default
construction, and adding default construction into the mix would likely
cause some confusing corner cases and generally not work very well.

The fact that D has default initialization is extremely useful (e.g. it
makes it impossible to have issues like variables being initialized with
garbage unless you specifically tell the compiler to do it with something
like initializing with = void;), but the fact that you can't have default
constructors for structs is at times quite annoying. So, it comes at a cost,
but the tradeoff is arguably well worth it.

In general, it's advised to simply not declar structs that require that they
be default constructed rather than default initialized, but you can declare

@disable this();

to disable default construction and then use a factory method to construct
the type instead of using a constructor directly. However, this does have
the downside that you can't use the struct anywhere that default
initialization is required (e.g. in an array), and an init value still
exists for the type and can be assigned to it (which functions like
std.algarothim's move will do). So, if the type can't handle being assigned
its init value, you may still have problems in some cases. As such,
disabling default initialization really isn't something that should be done
unless you really need to, but like = void;, the language does provide it
for cases where it really is needed, and the programmer is careful.

- Jonathan M Davis





More information about the Digitalmars-d mailing list