|
|
|
|
|
by wvenable
4336 days ago
|
|
RAII simply requires that resource allocation is tied to object lifetime. It requires that destructors are called deterministically and immediately once all references to an object no longer exist. (In the case of cycles, a reference remains until otherwise broken -- a non-issue for this definition). I personally prefer RAII to finally for object-related cleanup because finally is fallible. If you have a File object instance whose destructor calls fclose() automatically then I don't have to remember to call a Close() method inside a finally block. It happens automatically. But if you don't have RAII then you must remember to put in try blocks and finally clauses everywhere you create an instance. Multiply that by every database connection, network connection, and file and that is a lot of work and potential to miss something. And finally doesn't work at all if your object lifetimes aren't tied to scope. Finally is inferior to RAII in almost all cases except where you aren't using nicely defined objects. If you use an fopen() call directly, finally is your only recourse to fclose() it properly. The only criticism of RAII is that does limit concurrency and garbage collection options. |
|
I agree with your points about "finally". It can definitely be a bit clunky, and this is why some languages have introduced scoped cleanup constructs such as C#'s "using" statement, Python's "with" statement, and D's "scope" statement. I guess what I was getting at with my original comment is that I feel scoped cleanup constructs are a better way to go vs. relying on heap allocated things being reclaimed at a certain time, given that the lifetime of a heap allocated thing can depend on non-local state outside of the current function/method.