简体   繁体   中英

Idiomatic way to determine if an object has been destroyed

I've been trying to find a better way to accomplish determining if a particular object has been destroyed ( destroy(...) ). The way I've been doing it is like so:

class C { 
  bool valid = false; 
  this(){
    valid = true; 
  } 
}

Then you do:

C c = new C;
c.valid.writeln // true
destroy(c);
c.valid.writeln // false
if(c !is null && !c.valid) c = null;

I don't see anything wrong with this (perhaps someone can tell me something else wrong with it) other than that it takes up memory and requires putting valid = true; in each constructor (and is ugly because it uses a variable from a destroyed object). The best case, of course, would be to have some magical function that can just tell you if some object is valid or not valid(c); // true / false valid(c); // true / false .

So my question is if there is some standard way to determine if the object has been destroyed (like, the gc hasn't collected that memory location and a valid object is sitting in that spot without a reference to a vtable) and that the pointer is now virtually dangling? If there isn't any good way to do this then as a secondary question: is this method dangerous in any foreseeable way?

Previously, I made sure that for each reference from object A -> B there was a reference B -> A, and upon applying destroy A's destructor nullified B's reference to A. So I never even had to check if A was destroyed. But this is very tedious and time consuming when you want to add a new type of reference because you have to modify both the destroyable class (A) and the referencing class (B). Theoretically, this is something like always having a determinable cycle in the reference graph of your program (or something like that); it is potentially a very interesting subject.

Sorry in advance if I'm being an idiot.

By default D will use GC to deal with reference types (class in your case). This means that if you use defaults, you can't expect deterministic object destruction.

Jonathan explained that nicely in this thread: Usage preference between a struct and a class in D language

If you really need deterministic destruction - use structs. The method you described reminds me of Scala's Option type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM