struct and default constructor

Walter Bright via Digitalmars-d digitalmars-d at puremagic.com
Fri Oct 10 02:58:39 PDT 2014


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.



More information about the Digitalmars-d mailing list