Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is RAII and garbage collection mutually exclusive?

While I think I understand the gist of the problem (i.e. a good GC tracks objects, not scope), I don't know enough about the subject to convince others.

Can you give me an explanation on why there are no garbage-collected languages with deterministic destructors?

like image 856
György Andrasek Avatar asked Jan 12 '11 18:01

György Andrasek


1 Answers

They are NOT mutually exclusive. Feel free to use C++ with libgc (Boehm-Reiser-Detlefs collector). You can still use RAII, smart pointers, and manual deletion, but with the GC running you can also just "forget" to delete some objects.

@Andy's answer regarding resources being disposed too late misses the important point: it isn't the delay releasing resources which is crucial semantically, but rather the order of release.

The reason GC tends not to order release well is that it would require a topological sort on ordering requirements (dependencies) and that's an expensive algorithm.

Nevertheless Ocaml GC has an interesting facility where you can attach a finaliser to an object. If the object becomes unreachable the finaliser is run, however the object is not deleted (because the finaliser could make it reachable again: in that case you can even attach another finaliser). These finalisers can provide some control over ordering.

like image 93
Yttrill Avatar answered Oct 26 '22 10:10

Yttrill