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 08:30:01 PST 2014
On Sunday, 14 December 2014 at 16:05:13 UTC, Dan Olson wrote:
> "Marc "Schütz\"" <schuetzm at gmx.net> writes:
>
>> 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`.
>
> In this case the object cannot be collected by gc because there
> is still
> a good reference to it (variable 'a'). I agree if delete was
> used
> instead of destroy that is would be unsafe.
> --
> dano
Right, but I see it only as a simplified example. In a real
program, that reference will most likely be a member of object
whose destructor is being run.
More information about the Digitalmars-d-learn
mailing list