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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With