Le 25/07/2012 11:51, Jonathan M Davis a écrit :
On Wednesday, July 25, 2012 11:34:12 monarch_dodra wrote:
According to TDPL, the rationale for structs not having default
constructors is "T.init", were T.init is defined as:
*A static, known at compile time, mem-copyable value.
*The value that gets mem-copied into structs before the
constructors are called
*The value that gets mem-copied into structs when moving stuff
out of them.
**Destructors must support being called on a T.init element.

The thing is, I can't, for the life of me, understand how that
interferes with having a default constructor. Wouldn't keeping
the current definition of init, but allowing a call to a "no-arg"
constructor after after the mem-copy of T.init also work? As long
as the destructor keeps supporting calls to T.init objects, then
all is fine. Why hold out on a very useful functionality?

Am I missing a case where having a default constructor could
actually mess things up? The restriction just feels gratuitous
for me.

If you want to be able to do S(), then declare a static opCall for S which
returns an S constructed in the way that you want.

struct S
{
     static S opCall()
     {
         //do whatever you do
         return s;
     }
}

auto s = S();

but

S s;

will always be init. But you can't have a default constructor, because then it
conflicts with what init would be doing. e.g. would

S s;

be initialized with init or with the default constructor? But the static
opCall does let you construct a struct without any arguments. You just can't
have anything which isn't explicitly constructed using a default constructor,
because that's init's job.

Also, because all types must have an init value, if you can't guarantee that
your struct is valid and usable with its init property, then you'll either
have to disable the struct's init value so that it cannot be use

struct S
{
     @disable this();
}

or you'll have to live with the fact that using it could blow up in your face
- which really isn't all that different from other types (e.g. float.init is NAN
and pointers default to null).

- Jonathan M Davis

Static opCall isn't a solution. You can't new on it. And it seems weird that you can disable something that don't possibly exists in the first place.

This topic comes back again and again on the NG, it have to be considered.

If I get a concrete example, let say RefCounted, I can see in the source code that many checks are performed to handle the case where the struct is .init . It have a runtime cost and make the code more complex.

It is more error prone because specific cases must be handled all over the place. Having .init is certainly an interesting capability of D, but in this specific case, it isn't sure it worth it.

Reply via email to