On Sunday, 2 October 2022 at 16:21:47 UTC, data pulverizer wrote:
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's because `writeln` is copying the object, and each of the copies is being destroyed. If you add a copy constructor to your example, you can see it happening:

```d
import std.stdio: writeln;

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



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

Output:

```d
Object copy constructor...
Object copy constructor...
Object copy constructor...
Object copy constructor...
MyObject(0)Object destructor ...
Object destructor ...

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

Object destructor ...
```

Reply via email to