Question about RAII.

Derek Parnell derek at nomail.afraid.org
Tue Jul 4 16:32:08 PDT 2006


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.

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 );
    }

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
5/07/2006 9:24:10 AM



More information about the Digitalmars-d mailing list