Search code examples
javac++garbage-collectionsmart-pointers

C++: would universal use of shared_ptr<> be equivalent to a gc?


This is just an academic question (I would never do this in real code):

If I were to use shared_ptr<> universally in my code, would the behavior be equivalent to a gc-collected language like Java?

If not, how would the behavior be different from a gc-embedded language? Which C++ construct would yield equivalent behavior compared to a gc-embedded language?

Note: In real coding, I strongly prefer the use of RAII and strict ownership over the use of any smart pointers. I also know that other less-generic pointers, unique_ptr<> would be more efficient. This question is just a query into smart-pointer equivalence.


Solution

  • No, there'd be a couple of important differences:

    • You would get a memory leak any time you have a cyclic reference. A garbage collector can handle cycles, ref-counting can't.
    • You would avoid any stalls or pauses because no garbage collection ever occurs. On the other hand, you'd likely spend more total CPU time cleaning up resources, because the amortized cost of an occasional garbage collection is pretty low, and ref-counting can be relatively expensive if you do it on everything.

    Obviously the first point is the killer. If you did this, many of your resources wouldn't get freed, and you'd leak memory and your app just wouldn't behave very well.

    Which C++ construct would yield equivalent behavior compared to a gc-embedded language?

    None. C++ doesn't have a garbage collector because there's no way to implement a correct, reliable one. (Yes, I'm aware of Boehm's GC, and it's a good approximation, but it's conservative, and doesn't detect all references, only the ones it can be 100% sure of. There is no way, in a general C++ program, to implement a garbage collector that Just Works(tm))