Question about Object.destroy

Lambert Duijst via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Sep 20 11:52:15 PDT 2015


On Sunday, 20 September 2015 at 18:39:57 UTC, Adam D. Ruppe wrote:
> On Sunday, 20 September 2015 at 18:34:37 UTC, Lambert Duijst 
> wrote:
>> Oh that surprises me a bit, because I read in the list of 
>> deprecated features that delete is deprecated and that the 
>> right thing to do is to use destroy instead.
>
> Right. One of the benefits of destroy is that it nulls the 
> reference. Once you destroy it, you aren't supposed to use it 
> again*. The zombie is kept around until the GC reaps it to 
> protect against dangling pointers (somewhat), but you still 
> aren't actually supposed to reuse it.
>
> * If you really want to you can cheat by making a separate 
> local variable to hold it before destroy it... destroy only 
> nulls the variable you pass in, but I do not recommend doing 
> this. Instead, you should reconstruct the object, even if 
> implementing an object pool or something.
>
>> I use writeln("Address of s ", &s) to print the address, not 
>> sure if that is correct though.
>
> that gives you the address of the local variable, not the 
> reference. For address of the reference, try `cast(void*) s`.
>
> An Object in D is like an Object* in C++. So when you & it, you 
> get a pointer to a pointer.

Ah, that clarifies a lot ! Thanks. Also does destroy set all 
references to that object to null in this case there was only 1, 
but in a real program there can of course be many references to 
an object.

I wasn't interested in reusing an object after it was deleted, 
but more in the behaviour of a program if you do use it after a 
deletion. Just want to know if D protects against dangling 
pointers or is this just something you should never do.

If we are not supposed to use Object.destroy anymore then how can 
we still free non-memory resources that are held by classes 
(which are typically cg'ed) in a deterministic way ?



More information about the Digitalmars-d-learn mailing list