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

Dan Olson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Dec 13 09:13:34 PST 2014


"Andrey Derzhavin" <vangelisforever at yandex.ru> writes:

> Hello!
>
> We have object, for example, objA.
>
> ObjectAType objA = new ObjectAType(...);
>
> // we have a many references to objA
>
> void someFunction1(...)
> {
>    // destroying the objA
>    destroy(one_of_the_refToObjA);
>
>    //........
> }
>
>
> void someFunction2(....)
> {
>    // "segmentation fault" if the objA is destroyed
>    another_refToObjA.method1();
>
>    // I need a safe way (without using signals) to detect whether
> object
>    // destroyed or not, like this
>    // if (!isDestroyed(another_refToObjA))
>    //   another_refToObjA.method1();
>
> }
>
> // call functions
> someFunction1(..);
>
> // ..... some other operations...
>
> // the objectA (objA) is destroyed, but debugger shows us a not null
> reference
> // to that objA. However, when we try to call some methods of objectA
> or
> // try to use it's variables we get a "segmentation fault" error (in
> // someFunction2, when objA is destroyed).
> someFunction2(...);
>
> Thanks.

Maybe this would work for you.  If you own your ObjectAType class, you
could add an ok flag.  destroy() sets all members to .init value and
TDPL says this will be the case (lookup "clear" which was renamed
"destroy").

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.
}

--
dano


More information about the Digitalmars-d-learn mailing list