

Ask HN: Is RAII sufficient for memory management? - ekiru

In C++ the RAII idiom is common for managing memory. Any resources(such as heap memory or files) needed are acquired in the constructor of an object and releases in the object's constructor. Since stack-allocated objects destroyed automatically upon leaving scope this ensures that the resources are released.<p>Are there any memory management scenarios for which this is insufficient and for which garbage collection is necessary?Are there any other memory management techniques(other than GC, RAII, or manual memory management) which would be more effective for those scenarios?
======
mbrubeck
RAII doesn't provide an obvious, simple way to release memory in the presence
of cyclic references. You may be able to use weak references to fix this, but
that requires the programmer to notice the problem and explicitly specify the
solution. Automatic GC takes the burden off the programmer in this case. (On
the other hand, RAII provides for greater control, and works for resources
other than memory too. Both techniques are useful tools.)

~~~
ekiru
In some instances of cyclic references, specifically those in which only one
of the objects need be stack-allocated and in which none of the objects will
be passed into a higher scope. For example, one may find it useful in a tree
class to keep a reference to each node's parents. Despite this cyclic
reference, however, if you have a local variable which holds the top node of a
tree it will, upon leaving scope, be destroyed. If its destructor recursively
deletes the subtrees, RAII works despite the circular references.

However, you're right that in more complex scenarios, RAII doesn't deal with
reference cycles.

The ideal situation would be a language in which one could use either garbage
collection or static allocation with RAII as the situation demands.

