struct and default constructor

Simon A via Digitalmars-d digitalmars-d at puremagic.com
Fri Oct 10 17:25:49 PDT 2014


On Friday, 10 October 2014 at 09:58:54 UTC, Walter Bright wrote:
> On 11/27/2011 11:53 AM, deadalnix wrote:
>> I wonder why struct can't have a default constructor. TDPL 
>> state that it is
>> required to allow every types to have a constant .init .
>
> Having a .init instead of a default constructor has all kinds 
> of useful properties:
>
> 1. the default object is trivially constructable and cannot fail
>
> 2. an easy way for other constructors to not have overlooked 
> field initializers, so they get garbage initialized like in C++
>
> 3. generic code can rely on the existence of trivial 
> construction that cannot fail
>
> 4. dummy objects can be created, useful for "does this compile" 
> semantics
>
> 5. an object can be "destroyed" by overwriting it with .init 
> (overwriting with 0 is not the same thing)
>
> 6. when you see:
>     T t;
> in code, you know it is trivially constructed and will succeed
>
> 7. objects can be created using TypeInfo
>
>
> Default constructors are baked into C++. I can't escape the 
> impression that the desire for D default constructors comes 
> from more or less trying to write C++ style code in D.
>
> I feel that non-trivial default construction is a bad idea, as 
> are the various methods people try to get around the 
> restriction. For non-trivial construction, one can easily just 
> make a constructor with an argument, or call a factory method 
> that returns a constructed object.

I've often thought that most of the hidden pain of arbitrary
constructors in C++ could be avoided if C++ could take advantage
of functional purity.

D has native functional purity.  Couldn't you get the same
benefits that you listed by allowing default constructors but
requiring them to be pure?  Of course, you can get the same
outcome by initialising members using static pure functions or
various other helpers, so you could say that pure default
constructors are just syntactic sugar.

Pure default constructors do have some advantages for more
complex construction, though.  For the sake of example, say I
have a struct that uses a table of complex numbers, and for
unrelated reasons the real and imaginary parts are stored in
separate arrays.  I.e., I have to initialise multiple members
using one calculation.  Adding pure default constructors to D
would allow this to be implemented more cleanly and more
intuitively.


More information about the Digitalmars-d mailing list