this() in struct
Jonathan M Davis
jmdavisProg at gmx.com
Tue Oct 9 11:04:05 PDT 2012
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
More information about the Digitalmars-d-learn
mailing list