www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Custom delete not getting called

reply d coder <dlang.coder gmail.com> writes:
Hello People

I was just trying out custom memory allocation/deallocation that can be
found on the link
http://www.d-programming-language.org/memory.html#newdelete

The problem is that the delete function is never getting called. I have put
an example test case at the end of the email.

Any ideas?

Regards
- Puneet



import core.memory : GC;
import std.stdio;
import std.exception; // enforce

class Foo {
  string value = ".";

  new(size_t sz) {
    write("+");
    void* p = enforce(GC.malloc(sz),
      "Out of memory while allocating Foo");
    GC.addRange(p, sz);
    return p;
  }

  delete(void* p) {
    write("-");
    if (p) {
      GC.removeRange(p);
      GC.free(p);
    }
  }
}

void main() {
  for (size_t i = 0; i < 32; ++i) {
    Foo foo = new Foo();
    write(foo.value);
  }
}
Jun 24 2011
parent reply Ali =?iso-8859-1?q?=C7ehreli?= <acehreli yahoo.com> writes:
On Sat, 25 Jun 2011 09:23:19 +0530, d coder wrote:

 Hello People
 
 I was just trying out custom memory allocation/deallocation that can be
 found on the link
 http://www.d-programming-language.org/memory.html#newdelete
 
 The problem is that the delete function is never getting called. I have
 put an example test case at the end of the email.
 
 Any ideas?
 
 Regards
 - Puneet
There is no guarantee that if and when the destructor or the custom delete will be called on garbage collected objects. If they do get called, the call order is not deterministic. You can define the objects as 'scope' to force their destructors to be called when exiting the scope:
 void main() {
   for (size_t i = 0; i < 32; ++i) {
     Foo foo = new Foo();
scope Foo foo = new Foo();
     write(foo.value);
   }
 }
Ali
Jun 24 2011
parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On 2011-06-24 23:01, Ali =C7ehreli wrote:
 On Sat, 25 Jun 2011 09:23:19 +0530, d coder wrote:
 Hello People
=20
 I was just trying out custom memory allocation/deallocation that can be
 found on the link
 http://www.d-programming-language.org/memory.html#newdelete
=20
 The problem is that the delete function is never getting called. I have
 put an example test case at the end of the email.
=20
 Any ideas?
=20
 Regards
 - Puneet
=20 There is no guarantee that if and when the destructor or the custom delete will be called on garbage collected objects. If they do get called, the call order is not deterministic. =20 You can define the objects as 'scope' to force their destructors to be =20 called when exiting the scope:
 void main() {
=20
   for (size_t i =3D 0; i < 32; ++i) {
  =20
     Foo foo =3D new Foo();
=20 scope Foo foo =3D new Foo(); =20
     write(foo.value);
  =20
   }
=20
 }
That version of scope is going away. Use std.typecons.scoped instead. =2D Jonathan M Davis
Jun 25 2011