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

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Dec 15 07:48:09 PST 2014


On 12/13/14 2:03 AM, Andrey Derzhavin wrote:
> 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(...);

Yes, you can tell if the typeinfo pointer is null, this is how the 
runtime does it.

Unfortunately, typeid(objA) uses the pointer to look up the most derived 
type and results in a segfault.

You can use the knowledge of the object layout (the typeinfo pointer is 
the first item in the memory block) to ascertain whether it's null or 
not, it's what the runtime does:

bool isDestroyed(Object o)
{
    return o is null || *(cast(void **)o) is null;
}

Although, I highly recommend not doing this. Instead of destroying an 
object, leave the object live and dispose of it using some other method 
(e.g. close, dispose, etc.). Then let the GC clean up the memory later 
when nothing refers to it.

-Steve


More information about the Digitalmars-d-learn mailing list