Why is a static struct's dtor called at the exit of a function?

Jonathan M Davis jmdavisProg at gmx.com
Sat Jul 23 02:24:30 PDT 2011


On Saturday 23 July 2011 08:52:28 Andrej Mitrovic wrote:
> What are the current semantics of static struct definitions in module
> scope? It doesn't seem to have any effect. I was thinking about this:
> 
> module test;
> 
> int z;
> 
> static struct Foo
> {
>     void foo()
>     {
>         z = 5;  // maybe make this an error if the struct definition is
> static? }
> }
> 
> Maybe it could be useful as protection against modifying globals.

static only affects what can be accessed when it's on something that's nested. 
It affects member functions (which are nested in a class or struct), making it 
so that it can't access the surrounding class or struct. The same goes with 
nested structs and classes. When used on a function, struct, or class inside 
of a function, it makes it so that that nested function, struct, or class 
cannot access the scope of the function that it's in. It _never_ has any effect 
on global variables, and it _never_ affects _anything_ at module scope.

The struct above isn't nested in anything, so static makes no sense for it. 
And if you tried to make it so that it so that its functions then couldn't 
acces the module's scope, that would be completely inconsistent with 
everything else. The only time that a function cannot access a variable at 
module scope is when that function is pure. You're essentially suggesting that 
static be used to do pure's job in this case.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list