Are there any methods like isDestroyed or isDisposed to detect whether some object is destroyed or not?

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Dec 14 03:07:05 PST 2014


On Saturday, 13 December 2014 at 21:20:43 UTC, Andrey Derzhavin 
wrote:
>>
>> import std.stdio;
>>
>> class ObjectAType {
>>    bool ok;
>>    this() {ok = true;}
>> }
>>
>> void main()
>> {
>>    auto a = new ObjectAType;
>>    assert(a.ok);
>>    destroy(a);
>>    assert(!a.ok);  // a has been destroyed.
>> }
>>
>
> This method of detection of collected objects is what I needed.
> Thanks to everybody for your advise.

Be careful - the memory could still have been reused. For example:

     assert(a.ok);
     destroy(a);
     // ... lots of code, maybe multi-threaded ...
     assert(!a.ok);    // can fail

If between `destroy()` and the second `assert()`, the memory of 
the object is collected, a new object (of the same or different 
type) can have been placed there. You will then read an arbitrary 
piece of data from that new object, which may or may not evaluate 
to `true`.

The only case where this can be safe is when you can guarantee 
that there are no new memory allocations between the destruction 
and the test, or that the GC doesn't run. The first condition may 
also be no longer sufficient if the GC starts moving objects 
around (the current one doesn't).

Really, in practice you just cannot safely access GC managed 
resources from inside a GC destructor. You're just asking for 
trouble if you try to hack around that fact.


More information about the Digitalmars-d-learn mailing list