null [re: spec#]

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 8 09:52:08 PST 2010


On Monday, November 08, 2010 05:01:57 Simen kjaeraas wrote:
> Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> > ??? Structs have no default constructor.
> 
> True. Disabling the default constructor here means that
> 
> struct Foo{
>      @disable this();
> }
> Foo f;
> 
> should halt compilation at Foo f;, and certain other places where a
> default constructor would normally be used.

I was not aware of that. I didn't think that you could do that for structs since 
default constructors are illegal in the first place. It would likely have the 
negative side effect of making it illegal to put Foo in arrays though, since it 
wouldn't be possible to fill in the array values with init.

> > They have an init property with is used for default initialization.
> 
> Indeed. And this is different from a default constructor that you can't
> touch how?

Default initialization is used all over the place - including both stuff like the 
declaration Foo f; and in array declarations. Every type is default initialized 
when not initialized directly, and it has nothing to do with default 
constructors. init must be known at compile time whereas default constructors 
are run at runtime.

Now, if disabling this() on a struct makes init unuseable, then it does become 
possible to disallow init, which is potentially very useful, but it could also 
become a problem with arrays and the like. Regardless, while default 
constructors and init may be similar for structs, since structs are value types 
and don't _have_ default constructors, they still aren't the same thing. init is 
essentially the value _before_ any constructor is called. You just can't have a 
default one.

> > Either init needs to be changed to allow for real default constructors
> > and/or objects need to be legal CTFE - ideally both.
> 
> Disabling the default constructor (which ostensibly looks this:
> this( ) { this = init; }) is a very good step in the right direction.
> Having proper default constructors would be better, and I can not
> remember the reason we don't have that.

It's because we need init, and init must be known at compile time. init gets 
used a fair bit (such as when you declare an array of a given size and the 
compiler _must_ initialize all of its elements), and it's vital to how D 
functions. However, D isn't currently able to insert any code which runs for any 
init values to default construct them. init must be entirely known at compile 
time. Depending on exactly how init works, it could be a _huge_ change to try 
and make a default constructor run instead.

init makes a lot of sense as it stands for all types _except_ for structs, but 
it's definitely problematic for structs.

- Jonathan M Davis


More information about the Digitalmars-d mailing list