raii
Jonathan M Davis
jmdavisProg at gmail.com
Sun Feb 28 13:42:16 PST 2010
Ellery Newcomer wrote:
> On 02/28/2010 02:34 PM, sybrandy wrote:
>> <snip>
>>
>> I have two questions for you:
>>
>> 1) Are class destructors not good enough? If so, why?
>
> They might be good enough, I don't know. I thought they wouldn't be
> guaranteed to be called on scope exit, though.
>
>>
>> 2) Have you looked into static destructors? I created a logging library
>> and that worked perfect for me to ensure that if I killed the program
>> via Ctrl-C, it would flush the output buffer and close the file handle.
>
> I'm not really looking at unexpected terminations
>
>>
>> Personally, I really like the use of "scope" vs. RAII. Keeping the code
>> to clean up a file handle or the like right by where it's declared seems
>> very sensible to me.
>
> I like scope too. But it's still something the user has to remember.
>
>>
>> Casey
Without RAII, it's likely something that they have to remember too. Unless
they specifically call close or whatever it is that's supposed to be done
when the object leaves scope, it won't happen. scope is just a better way to
explicitly make it happen without worrying about things like exceptions.
If you want to guarantee that something will be destroyed when it leaves
scope, you're going to have to go with a struct, since that's guaranteed by
the language - the user of your struct can't forget it like they can with
scope and classes.
I like scope, but it's something that the person using the class has to
remember just like they'd have to remember to call the close function or its
equivalent if there were no scope modifier. It's just the nature of classes.
And really, it's not all that different from C++. It's just D's way of
declaring classes on the stack but with the benefit that you're not passing
objects around on the stack and incurring those copying costs.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list