Unittests pass, and then an invalid memory operation happens after?

H. S. Teoh hsteoh at qfbox.info
Wed Mar 27 22:14:16 UTC 2024


On Wed, Mar 27, 2024 at 09:43:48PM +0000, Liam McGillivray via Digitalmars-d-learn wrote:
[...]
> ```
>     ~this() {
>         this.alive = false;
>         if (this.map !is null) this.map.removeUnit(this);
>         if (this.faction !is null) this.faction.removeUnit(this);
>         if (this.currentTile !is null) this.currentTile.occupant = null;
>     }
> ```
[...]

What's the definition of this.map, this.faction, and this.currentTile?

If any of them are class objects, this would be the cause of your
problem.  Basically, when the dtor runs, there is no guarantee that any
referenced classed objects haven't already been collected by the GC. So
if you try to access them, it will crash with an invalid memory access.

In general, it's a bad idea to do anything that relies on the dtor being
run in a particular order, because the GC can collect dead objects in
any order.  It's also illegal to perform any GC memory-related
operations inside a dtor (like allocate memory, free memory, etc.)
because the GC is not reentrant.

If you need deterministic clean up of your objects, you should do it
before the last reference to the object is deleted.


T

-- 
He who does not appreciate the beauty of language is not worthy to bemoan its flaws.


More information about the Digitalmars-d-learn mailing list