About RAII and GC...?
Nick Sabalausky
a at a.a
Mon Jul 30 19:15:19 PDT 2007
"Robert Fraser" <fraserofthenight at gmail.com> wrote in message
news:f8m283$2q9b$1 at digitalmars.com...
> Nick Sabalausky Wrote:
>
>> Maybe I'm misunderstanding things, but if you use RAII wherever
>> appropriate, wouldn't that eliminate the need for garbage collection? Is
>> there something I'm missing here?
>
> If the only resource you're acquiring at construction is memory (90% of
> cases), you can just use the GC instead. Also, the GC isn't necessarily
> incompatible with RAII -- if there's some resource you don't need to
> release as soon as possible, the GC will run the destructor on its own.
That's not exactly what I'm asking. I'll explain:
As we know, the reason for having garbage collection is that when using
malloc/new there's a general tendency to forget the occasional free/delete
(or end up with an exectution path that accidentially omits it), thus
causing memory leaks. GC, of course, fixes that by saying "Don't worry about
freeing, I'll clean up after you".
Now, maybe I'm misunderstanding RAII, but as I understand it, RAII
guarantees that allocated memory (or whatever resource) gets freed
automatically whenever the owning object goes out of scope.
So that seems to indicate to me that RAII is not only more general than GC
(ie, can work for more than just memory) but also lacks any overhead of
having a GC (aside from the usual overhead of freeing a resource). Thus,
RAII can effectively replace the use of a GC.
Of course, with RAII you still need to manually release resources (right?),
but you only need to do it in the destructor (right?). And this is vastly
easier to not screw up than having "new"s and "delete"s all over the place.
So, does my analysis of this make sense, or am I off-base?
More information about the Digitalmars-d
mailing list