www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Struct destructors not always called?

reply Jeremy DeHaan <dehaan.jeremiah gmail.com> writes:
I was playing around with some code today and I noticed that in 
some cases struct destructors are not called.

for example:

impost std.stdio;

SomeStruct global;

void main()
{
    SomeStruct inMain;
    writeln(global.thing);
    writeln(inMain.thing);
    writeln(getSomeInt());
}

int getSomeInt()
{
     static SomeStruct inner;
     return inner.thing;
}

struct SomeStruct
{
     int thing = 100;
     ~this()
     {
         writeln("destructor");
     }



output is
100
100
100
destructor

Only inMain's destructor is ever called, or at least it is the 
only one that ever prints "destructor" to the console. Are there 
special rules for structs that I'm unaware of?
Dec 27 2015
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Sunday, 27 December 2015 at 18:40:55 UTC, Jeremy DeHaan wrote:
 I was playing around with some code today and I noticed that in 
 some cases struct destructors are not called.
struct destructors are called when the struct ceases to exist in the program. A global variable never ceases to exist as long as the program lives.
Dec 27 2015
parent reply Jeremy DeHaan <dehaan.jeremiah gmail.com> writes:
On Sunday, 27 December 2015 at 18:47:52 UTC, Adam D. Ruppe wrote:
 On Sunday, 27 December 2015 at 18:40:55 UTC, Jeremy DeHaan 
 wrote:
 I was playing around with some code today and I noticed that 
 in some cases struct destructors are not called.
struct destructors are called when the struct ceases to exist in the program. A global variable never ceases to exist as long as the program lives.
So are these left dangling or do they actually get cleaned up at the program exit?
Dec 27 2015
parent Adam D. Ruppe <destructionator gmail.com> writes:
On Sunday, 27 December 2015 at 19:04:11 UTC, Jeremy DeHaan wrote:
 So are these left dangling or do they actually get cleaned up 
 at the program exit?
They are left dangling right now. You can clear it yourself by defining a `static ~this() { .destroy(your struct); }` somewhere in the module. Maybe that should be done automatically but right now the assumption is those global structs are still available in the static dtors so they are considered alive right up to the program actually exiting... at which point no more code can run since the process has terminated....
Dec 27 2015