Cyclic depency with class static ctor
Jarrett Billingsley
kb3ctd2 at yahoo.com
Mon Oct 30 17:14:22 PST 2006
"Walter Bright" <newshound at digitalmars.com> wrote in message
news:ei6795$2d76$1 at digitaldaemon.com...
> It can appear that way, but there is a crucial point about static
> constructors. They are most useful when you import a module, and that
> module *may* or *may not* have some initialization needs that are hidden
> to you. Static constructors take care of that automatically.
That's true. Though more times than not, I've run into the cyclic import
problem..
> The problem here crops up only when they are cyclic imports, i.e. imports
> that import each other. That means the programmer implementing N that
> imports M is already familiar with the implementation of M, because M
> imports N. Therefore, there is no unknown static constructor nor are there
> any hooks that need to be added to main() by the programmer. Furthermore,
> the programmer can implement the static constructors for M and N in such a
> way that the user of M or N still does not need to add any hooks to
> main(). Essentially, M and N are logically welded into one module for the
> user.
It just seems like unnecessary cruft to have to do what Frank mentioned,
i.e. to create a "static ctor module" which calls all the static
initializations for all the modules in existence. It seems like the
compiler would be able to make a much better judgement call about which
static ctors depended upon which modules, and would be able to issue a
compile-time error if there really were a cyclic static ctor dependency
(which, 99% of the time, there _isn't_, which is why it seems completely
superfluous to have to manually initialize the modules!).
It makes me angry that I can't do something as simple as:
module a;
import b;
int x;
static this()
{
x = 5;
}
...............
module b;
import a;
int y;
static this()
{
y = 10;
}
There is obviously no interdependency between the modules for static
initialization, but D throws an error at runtime nonetheless. It seems
almost stupid.
More information about the Digitalmars-d
mailing list