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:34:53 PDT 2011


On Saturday 23 July 2011 11:28:07 Andrej Mitrovic wrote:
> Ok, so pure does the job, didn't know.

There are two requirements for a function to be pure:

1. Any functions that it calls must be pure.

2. It cannot access any static or global variables unless they're immutable or 
they're const value types (essentially, they can't access any static or global 
variables which could ever be changed over the course of the program).

So, if a function is pure, it can't access a global variable like in your 
example. Now, in addition to that, if a pure function's arguments can be 
determined to be guaranteed to be unchanged when the function is call, then 
that function is strongly pure, and additional calls to it with the same 
arguments in the same expression can be optimized out. At the moment, that 
means that the function's parameters must all either be immutable or 
implicitly convertible to mutable, but there are cases where the compiler 
could conceivably optimize it with just const (e.g. if an immutable variable 
is passed to a function where the parameter is const).

So, the primary thing that you get out of pure in the general case (since so 
many functions can be weakly pure but not strongly pure) is that you have the 
guarantee that it doesn't access global variables whose state is at all 
mutable.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list