| |
| Posted by Pavel \"EvilOne\" Minayev in reply to Sean L. Palmer | PermalinkReply |
|
Pavel \"EvilOne\" Minayev
Posted in reply to Sean L. Palmer
|
"Sean L. Palmer" <spalmer@iname.com> wrote in message news:9sdq5c$2bts$1@digitaldaemon.com...
> Just wondering what everybody thinks about being able to initialize static fields like so:
>
> class A
> {
> static int x = 0;
> static int y = 3;
> static this() {} // the above two initializations actually happen just
> before entry to static this()
> }
From D specification:
D makes this simple. All member initializations must be determinable by
the compiler at compile time, hence there is no order-of-evaluation
dependency for member initializations, and it is not possible to read a
value that has not been initialized. Dynamic initialization is performed
by a static constructor, defined with a special syntax static this().
class Foo
{
static int a; // default initialized to 0
static int b = 1;
static int c = b + a; // error, not a constant initializer
static this() // static constructor
{
a = b + 1; // a is set to 2
b = a * 2; // b is set to 4
}
}
> What about a similar syntax for initializing regular member fields?
And once again, D specs: In the class definition, the programmer can
supply a static initializer to be used instead of the default: class Abc
{
long bar = 7; // set default initialization
}
> might be nice to have the compiler warn about fields that are initialized
in> more than one way, to prevent the situations like when one programmer>
modifies the initialization inside the ctor and the other programmer>
modifies the initialization at point of field declaration.
I like the idea. When thing like that happens, it's very likely a bug,
in fact, so issue a warning for this seems logical.
> What about fields in structs? Can they have defaults? If structs could have even "compiler-generated" constructors, it'd be real nice.
Didn't found anything on this topic, so let's wait for the Guru's word =)
|