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

Jonathan M Davis jmdavisProg at gmx.com
Wed Jul 20 12:57:44 PDT 2011


On Wednesday 20 July 2011 21:54:19 Andrej Mitrovic wrote:
> import std.stdio;
> 
> void main()
> {
>     writeln("test");
>     test();
>     writeln();
>     writeln("test");
>     test();
> }
> 
> struct Foo
> {
>     int state;
>     this (int i)
>     {
>         state = i;
>     }
> 
>     ~this()
>     {
>         writeln("dtor");
>     }
> }
> 
> void test()
> {
>     static Foo foo = Foo(1);
>     writeln(foo.state);
> }
> 
> Prints:
> test
> 1
> dtor
> 
> test
> 1
> dtor
> 
> Shouldn't static variables be left untouched? I tried to use a struct
> to handle an external device context, however the dtor would be kept
> called between function calls, so this caused crashes for me.
> 
> Using a class instead fixes my issue of course.
> 
> I thought "static" for variables implied it has lifetime until the end
> of the application, regardless of whether the memory for the variable
> was allocated on the heap or is in the .data segment or somewhere
> else.

static variables are supposed to have essentially the same lifetime as the 
program. So, it definitely looks like a bug.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list