Am I crazy to recreate a tiny garbage collection system inside my functions?
c++, garbage-collection
Solution
You don't have to rely on garbage collection.
You have std::auto_ptr that provides pointer like syntax and wraps a dynamically allocated object. When destroyed, it automatically destroys the object it points to.
You could implement something similar for arrays.
Problem
I have some (C++) functions each containing several calls creating similar arrays of the same basic type on the heap. At various points in these functions, I may need to throw an exception. Keeping track of which arrays have been deleted is a pain, and quite error prone, so I was thinking about just adding the array pointers to a `Set<ArrType*>`, of which I can just delete every item when I catch an exception, like this: ``` try { set<ArrType*> sHeap; ArrType* myArr = new ArrType[5]; sHeap.Add(myArr); someExternalRoutine(myArr); ... } catch(CString s) { DeleteAllPointersInMyHeap(sHeap); throw(s); } ``` It feels a bit like adding epicycles, but I can't get around the fact that any one of several external calls may throw an exception, and I need to definitely delete all the pointers allocated up to that point. Is this just foolishness? Should I just add smaller try-catch blocks around the external calls? I'd still end up with little lists of delete A; delete B; delete D; after each one...