Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I crazy to recreate a tiny garbage collection system inside my functions?

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

like image 502
Phil H Avatar asked Jul 30 '09 15:07

Phil H


1 Answers

Why not use a smart pointer like boost::shared_array or use a stack-allocated std::vector? For single allocations rather than array allocations, you could use boost::shared_ptr.

These implement the RAII for you. Even if you're re-using a concept like RAII, you're still reinventing the wheel if there's already a concrete implementation out there that satisfies your requirements.

like image 164
Nick Meyer Avatar answered Nov 11 '22 01:11

Nick Meyer