Question about RAII.

Bruno Medeiros brunodomedeirosATgmail at SPAM.com
Tue Jul 4 17:36:54 PDT 2006


Derek Parnell wrote:
> On Tue, 4 Jul 2006 17:35:55 +0000 (UTC), Peter C. Chapin wrote:
> 
>> Oskar Linde <oskar.lindeREM at OVEgmail.com> wrote in
>> news:e8dqj5$29ns$1 at digitaldaemon.com: 
>>
>>> It looks like you want some kind of transfer semantics. You can do
>>> that manually:
>>>
>>>   if (f()) {
>>>      object3 = object1;
>>>      object1 = null;
>>>    }
>>>    else {
>>>      object3 = object2;
>>>      object2 = null;
>>>    }
>> That's a neat trick. Thanks. I can see that in many cases specifying which 
>> of the autos I don't want destroyed (in effect) would be easier than 
>> explicitly destroying everything else.
>>
>> Peter
> 
> Just checking, but doesn't setting an object reference to null just flag it
> as *available* for garbage collection, and isn't there no absolute
> guarantee that an object will actually be collected by the GC? In which
> case, you can't be certain that object1 or object2 will really have their
> destructor called. Whereas using the delete statement ensures the
> destructor call.
> 

I'm not sure if you're just asking that without regards to the previous 
code, you're if asking that because you may have misunderstood the 
previous code.
The point of setting those objects to null is not to collect it (if it 
was, indeed we couldn't be sure when the GC would collect), but indeed 
the opposite (to *prevent* collection). Because they are auto objects, 
the only to way to prevent (auto) collection is to setting them as null. 
Your example does work as well, of course.

> So I think that the code should be more like ...
> 
>    MyClass object1 = new MyClass( stuff1 );
>    MyClass object2 = new MyClass( stuff2 );
>    MyClass object3;
> 
>    if (f()) {
>       object3 = object1;
>       delete object2;
>     }
>     else {
>       object3 = object2;
>       delete object1;
>     }
> 
> Though given this simplistic example I'd actually code it more like ...
> 
>    MyClass object3;
> 
>    if (f()) {
>       object3 = new MyClass( stuff1 );
>     }
>     else {
>       object3 = new MyClass( stuff2 );
>     }
> 


-- 
Bruno Medeiros - CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list