How check if destructor has been called?
Christian Köstlin
christian.koestlin at gmail.com
Wed Sep 14 00:00:58 UTC 2022
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
More information about the Digitalmars-d-learn
mailing list