On Tuesday, 9 October 2012 at 18:29:18 UTC, Jonathan M Davis wrote:
On Tuesday, October 09, 2012 19:08:35 Zhenya wrote:
On Tuesday, 9 October 2012 at 17:21:47 UTC, Zhenya wrote:
> Hi!
> I'm sorry,maybe this topic already was discussed,but could
> anybody explain me
> why default constructor was disallowed in structs?

And if I have to do some initialization of data members,what is
the way to do it?

It's because of the init property. All types in D are default-initialized to their init property, and that property must be known at compile time (meaning that it doesn't work very well for it to involve a constructor). For structs, the init property is decided by what all of the member variables are directly
initialized to. So,

struct S
{
 int i = 5;
 string s = "hello";
}

assert(S.init == S(5, "hello"));

S s;
assert(s == S.init);

This has the unfortunate result that we don't get a default constructor. The
workaround is to declare a static opCall function.

struct S
{
 int i = 5;
 string s = "hello";

 static S opCall()
 {
 return S(22, "catch");
 }
}

S s;
assert(s == S.init);

S s2 = S();
auto s3 = S();
assert(s2 == S(22, "catch"));
assert(s2 == s3);

It doesn't make it so that the struct is default-initialized to the result of static opCall, and it doesn't guarantee that the result of static opCall is used when no constructor is called, but if you use S() explicitly, then it
will be used.

A solid design decision in the language (e.g. requiring that everything be default-initialized) can have the unfortunate side effect of restricting other choices, and in this case, mucks up default constructors for structs.

- Jonathan M Davis

Ok.Then,can I do my own .init property,that can be executed in compile time?

Reply via email to