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:

    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))