Stop writeln from calling object destructor

data pulverizer data.pulverizer at gmail.com
Sun Oct 2 16:21:47 UTC 2022


I've noticed that `writeln` calls the destructor of a struct 
multiple times and would like to know how to stop this from 
happening. It has become a very serious problem when working with 
objects that have memory management external to D.

Here is a repeatable example, where the destructor appears to 
have been called 4 times with one call of `writeln` before the 
object actually goes out of scope:


Code:
```
import std.stdio: writeln;

struct MyObject
{
     int id;
     this(int id) @nogc
     {
         this.id = id;
     }
     ~this()
     {
         writeln("Object destructor ...");
     }
}



void main()
{
     auto obj = MyObject(42);
     writeln("MyObject: ", obj);
     writeln("Goodbye:\n");
}

```

Output:
```
$ rdmd gc.d
MyObject: MyObject(42)Object destructor ...
Object destructor ...

Object destructor ...
Object destructor ...
Goodbye:

Object destructor ...
```

Thank you


More information about the Digitalmars-d-learn mailing list