C++ – RAII vs. Garbage Collector

cgarbage-collectionmemory-leakssmart-pointers

I recently watched a great talk by Herb Sutter about "Leak Free C++…" at CppCon 2016 where he talked about using smart pointers to implement RAII (Resource acquisition is initialization) – Concepts and how they solve most of the memory leaks issues.

Now I was wondering. If I strictly follow RAII rules, which seems to be a good thing, why would that be any different from having a garbage collector in C++? I know that with RAII the programmer is in full control of when the resources are freed again, but is that in any case beneficial to just having a garbage collector? Would it really be less efficient? I even heard that having a garbage collector can be more efficient, as it can free larger chunks of memory at a time instead of freeing small memory pieces all over the code.

Best Answer

If I strictly follow RAII rules, which seems to be a good thing, why would that be any different from having a garbage collector in C++?

While both deal with allocations, they do so in completely different manners. If you are reffering to a GC like the one in Java, that adds its own overhead, removes some of the determinism from the resource release process and handles circular references.

You can implement GC though for particular cases, with much different performance characteristics. I implemented one once for closing socket connections, in a high-performance/high-throughput server (just calling the socket close API took too long and borked the throughput performance). This involved no memory, but network connections, and no cyclic dependency handling.

I know that with RAII the programmer is in full control of when the resources are freed again, but is that in any case beneficial to just having a garbage collector?

This determinism is a feature that GC simply doesn't allow. Sometimes you want to be able to know that after some point, a cleanup operation has been performed (deleting a temporary file, closing a network connection, etc).

In such cases GC doesn't cut it which is the reason in C# (for example) you have the IDisposable interface.

I even heard that having a garbage collector can be more efficient, as it can free larger chunks of memory at a time instead of freeing small memory pieces all over the code.

Can be ... depends on the implementation.