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

Andrej Mitrovic andrej.mitrovich at gmail.com
Thu Jul 21 12:48:09 PDT 2011


On 7/21/11, Steven Schveighoffer <schveiguy at yahoo.com> wrote:
> On Wed, 20 Jul 2011 15:57:44 -0400, Jonathan M Davis <jmdavisProg at gmx.com>
> wrote:
>
>> 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.
>
> slight correction -- static variables are thread local (must be marked
> shared to be shared between threads), so the destructor should be called
> on Thread destruction.
>
> However, I don't think that any destructors are called on thread
> destruction...
>
> But yes, they should *definitely* not be called on function exit.  This is
> a bug.
>
> -Steve
>

Is this a known bug? I can't find anything about this in bugzilla. On
a related note, I had a dtor of a class not being called even with
explicit call to clear() or the older delete statement, and it wasn't
even called after application exit. But I have to make a minimal test
case first.


More information about the Digitalmars-d-learn mailing list