www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How check if destructor has been called?

reply Injeckt <vinsentlou9 gmail.com> writes:
Hi, I'm trying to check if destructor has been called, but when 
I'm deleting class object I didn't get any calls from destructor.

myclass.d

     ~this() {
         this.log("\nDestructor\n");
         this._free_trash();
     }


main.d

     try {
         server.server_init(server);
     } catch (Exception e) {
         server.log(e.msg);
         server = null;
     }
Sep 13 2022
parent reply Ben Jones <fake fake.fake> writes:
On Tuesday, 13 September 2022 at 14:06:42 UTC, Injeckt wrote:
 Hi, I'm trying to check if destructor has been called, but when 
 I'm deleting class object I didn't get any calls from 
 destructor.

 myclass.d

     ~this() {
         this.log("\nDestructor\n");
         this._free_trash();
     }


 main.d

     try {
         server.server_init(server);
     } catch (Exception e) {
         server.log(e.msg);
         server = null;
     }
Classes are allocated on the GC heap, so even though you're setting the reference to null, it's not being collected at that point. You can use `destroy` to make sure the destructor is called (see here: https://dlang.org/spec/class.html#destructors) Or you could make your instance `scope` and then it basically follows the same lifetime rules as `struct`s.
Sep 13 2022
parent =?UTF-8?Q?Christian_K=c3=b6stlin?= <christian.koestlin gmail.com> writes:
On 13.09.22 19:13, Ben Jones wrote:
 On Tuesday, 13 September 2022 at 14:06:42 UTC, Injeckt wrote:
 Hi, I'm trying to check if destructor has been called, but when I'm 
 deleting class object I didn't get any calls from destructor.

 myclass.d

     ~this() {
         this.log("\nDestructor\n");
         this._free_trash();
     }


 main.d

     try {
         server.server_init(server);
     } catch (Exception e) {
         server.log(e.msg);
         server = null;
     }
Classes are allocated on the GC heap, so even though you're setting the reference to null, it's not being collected at that point.  You can use `destroy` to make sure the destructor is called (see here: https://dlang.org/spec/class.html#destructors) Or you could make your instance `scope` and then it basically follows the same lifetime rules as `struct`s.
Some more things to watch out are mentioned in https://p0nce.github.io/d-idioms/#The-trouble-with-class-destructors. In one of my programs I had problems with allocating in GC called destructors (by doing "harmless" writeln debugging). Kind regards, Christian
Sep 13 2022