struct constructors and destructors.

Adam D. Ruppe via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 19 06:02:18 PDT 2017


On Wednesday, 19 July 2017 at 07:48:28 UTC, Danni Coy wrote:
> tries to OpAssign foo to itself then calls foo's destructor?

Are you sure that's what's actually happening?


What should be happening there is:

1) it calls Foo's constructor on a temporary location
2) it destroys the old contents of `foo`
3) it moves the Foo from (1) into the variable freshly destroyed 
from (2)


It is void initialized, so you might think there are no old 
contents of foo, but the compiler doesn't know this for certain 
(consider you called `open` twice. would be true the first time, 
but not the second time. the compiler needs to generate the 
function so it works both times).


There is a function which the compiler knows will only be called 
once though: a static constructor.

---
shared static this()
{
    foo = Foo("test");
}
---


That only runs once, and the compiler will skip the destruction 
of old `foo`.... as long as it isn't already initialized. 
Ironically, removing the `= void` from it causes the compiler to 
realize this and only use the ctor initialization. Otherwise, it 
tries to destroy the existing item, apparently not realizing it 
was void.... arguably a small compiler bug there.


More information about the Digitalmars-d mailing list