Struct constructor, opCall mess.

Maxim Fomin maxim at maxim-fomin.ru
Mon Feb 24 23:59:32 PST 2014


On Monday, 24 February 2014 at 14:14:43 UTC, Tobias Pankrath 
wrote:
> On Monday, 24 February 2014 at 13:56:01 UTC, Remo wrote:
>> Hi,
>>
>> right now I am truing to figure out how the constructors 
>> behave in D2.
>>
>> Question 1: why it is not possible to create custom ctor for 
>> struct?
>
> The design of D relies on the fact that every type has a T.init 
> property that is known to the compiler and used when in C++ the 
> default ctor would get called. In constructors you can rely on 
> (this == T.init), for example.
>
> You need to pick one T.init or default constructors and D 
> picked T.init.

The design of D relies on Andrei opinion. He is indeed convinced 
that default constructors are impossible.

However, you can write "default constructor" right now like:

struct S
{
    Type t;
    this(int)
    {
       t = whather_is_callable_in_CTFE();
    }
}

enum E : S
{
    A = S(0)
}

void main()
{
   E e;
   assert (e.t == whather_is_callable_in_CTFE());
}

Since compiler does this, it can also accept straight syntax and 
semantic:

struct S
{
    Type t;
    this() // proxibited default constructor now
    {
       t = whather_is_callable_in_CTFE();
    }
}

What D really lacks is ability to call function in runtime after 
struct instance creation like:

struct S
{
    @runtime this() {}
    ~this(){}
}

lowering to:
S s;
s.__runtime_ctor();

However, since compiler does this all over the place (postblits, 
copy constructors, destructors, etc.) There is no conceptual 
difference between having:

S s
s.__runtime_ctor();

and

S s;
s.__dtor();

In other words, there is no objective necessity not to have 
compile time and runtime default struct constructors since 
compiler already heavily does conceptually and technically 
similar things.


More information about the Digitalmars-d-learn mailing list