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

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 12 23:11:54 PST 2014


On Sat, 13 Dec 2014 07:03:22 +0000
Andrey Derzhavin via Digitalmars-d-learn
<digitalmars-d-learn at puremagic.com> 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(...);
> 
> Thanks.

first. you'd better to not write such code, it's completely unreliable.

second. you can check if the block is allocated by using GC.addrOf().

third. and this is completely unreliable, 'cause memory can be reused.

so the only right answer is: "don't do that!" use list of free objects,
for example, and write `free()` function that will move the object to
that list (and possibly set some flags to mark it as "freed").

let me stress it again: you *CAN'T* reliably detect if some object was
manually destroyed. don't even think you can do this in working code,
you will never made such code fully working.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20141213/c8666f39/attachment.sig>


More information about the Digitalmars-d-learn mailing list