Explicit default constructor for structs

Benjamin Thaut code at benjamin-thaut.de
Wed Apr 9 07:59:36 PDT 2014


Just to be clear, I don't want a default constructor for structs that 
gets called implictly by the compiler, like in C++.

Instead I would really love to have a explicit default constructor. E.g. 
it could look like this (alternative a new keyword "explicit" could be 
introduced, but introduction of new keywords is usually avoided if 
possible, AFAIK):

struct Foo
{
   this(void)
   {
     // do stuff here
   }
}

This default constructor would _never_ be called automatically by the 
compiler. (e.g. when a class is constructed that has struct members.) It 
would only be called in cases where the user explictly calls it.

The following lines would call the explicit default constructor

auto foo1 = Foo();
auto foo2 = new Foo();
foo1 = Foo(); // calls explicit constructor first, then calls assignment 
operator

Whereas the follwing would _not_ call the explicit default constructor.

class Bar
{
   Foo m_foo;
}
auto bar = new Bar();

Foo foo; // does not call the explict default constructor, because there 
is no explicit call here

I think this would fix all cases where you currently wish for a struct 
default constructor in D. Coupeled with "@disable this();" you could 
force users to always call one of the struct constructors. Currently I 
work around the issue of not having any default constructors by doing this:

struct DefaultCtor {}; //call default ctor type

enum defaultCtor = DefaultCtor();

struct Foo()
{
   @disable this();
   this(DefaultCtor)
   {
     // default constructor
   }

   this(int)
   {
     // other constructor
   }
}

auto foo = Foo(defaultCtor);

While this works, I'm getting anoyed by it every day. For example when 
refactoring types from Classes to Structs and vise versa. As well as 
when placing Classes on the stack using a helper struct. Or when having 
RAII structs that don't take any paramters in their constructor.

What do you think? C&C welcome.

Kind Regards
Benjamin Thaut






More information about the Digitalmars-d mailing list