Programming in D p288. Destructor called too many times.

Nick Treleaven nick at geany.org
Tue Feb 10 20:37:04 UTC 2026


On Monday, 9 February 2026 at 20:19:26 UTC, Brother Bill wrote:
> Console output:
> ```
> Creating Duration: 7:30:15
> Duration is: 07:30:15Destroying Duration: 7:30:15
> Destroying Duration: 7:30:15
>
> Destroying Duration: 7:30:15
> Destroying Duration: 7:30:15
> Destroying Duration: 7:30:15
> ```

If you add a copy constructor to Duration, you can see when it 
gets copied:
```d
	this(ref Duration d)
	{
		this.tupleof = d.tupleof;
		writeln("copying Duration: ", toString);
	}
```
I get:
```
Creating Duration: 7:30:15
copying Duration: 07:30:15
copying Duration: 07:30:15
Duration is: copying Duration: 07:30:15
copying Duration: 07:30:15
07:30:15Destroying Duration: 7:30:15
Destroying Duration: 7:30:15

Destroying Duration: 7:30:15
Destroying Duration: 7:30:15
Destroying Duration: 7:30:15
```
Each copy needs to get destroyed, as well as the original.


More information about the Digitalmars-d-learn mailing list