Why is a static struct's dtor called at the exit of a function?
Jonathan M Davis
jmdavisProg at gmx.com
Thu Jul 21 09:39:27 PDT 2011
On Thursday 21 July 2011 11:52:58 Steven Schveighoffer 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.
Ah, yes. There is that slight change in D from C++.
> However, I don't think that any destructors are called on thread
> destruction...
That doesn't sound good.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list