Hi all,

I have a question about the following piece of code that I wrote to experiment with explicit deletion of objects. I am interested in this because, even though D has a garbage collection, sometimes an object holds a non-memory resource, such as a file handle. In these cases explicit calls to a destructor are needed if you want deterministic release of resources.

The code I wrote is this :

import std.stdio;

class MyClass
{
  this(int a) {this.a = a;}
  ~this()
  {
    writeln("Destructor call");
  }

  void doSomething()
  {
    writeln("A is ", this.a);
  }
  int a;
};


void main(string args[])
{
  MyClass s = new MyClass(42);
  s.doSomething();
  s.destroy();
  s.doSomething();
}

The output of this program is:

A is 42
Destructor call

And then it segfaults.

This is obviously because of that last call to doSomething
Now the description of Object.destroy mentions that no GC memory is freed by Object.destroy. It does, however, put the object in an invalid state, but what does that mean and why does my program segfault.

Is it because:

- The GC did decide to run and cleanup memory straight after the call to s.destroy() - An object being in an invalid state means the program segfaults when the object is used ?
 - Another reason..

And more importantly, can this way of programming with explicit destroy calls lead to memory corruption due to dangling pointers ? or will D always let your program segfault whenever a deleted object is accessed ?

Please enlighten me, I am just a newbie :-)


Reply via email to