I have a function to allocate a 2D array in order to not to expend more memory than I need:
_>
template <class Xvar> Xvar** New2 (unsigned int rows,unsigned int cols)
{
Xvar** mem;
unsigned int size, i;
size = rows * cols;
mem = new Xvar* [rows];
mem [0] = new Xvar [size];
for (i=1;i<rows;i++)
mem [i] = &mem [0][i*cols];
return mem;
}
Now, I need to check if that memory is allocated. (handle memory allocation errors),
without decreasing the performance of the function.
Should I use a try-catch block for each memory allocation, or only a unique try-catch block for the function.
template <class Xvar> Xvar** New2 (unsigned int rows,unsigned int cols)
{
Xvar** mem;
unsigned int size, i;
size = rows * cols;
try {
mem = new Xvar* [rows];
}
catch (...) { assert (...) }
try {
mem [0] = new Xvar [size];
} catch (...) { assert (...) }
for (i=1;i<rows;i++)
mem [i] = &mem [0][i*cols];
return mem;
}
or something like:
template <class Xvar> Xvar** New2 (unsigned int rows,unsigned int cols)
{
try {
Xvar** mem;
unsigned int size, i;
size = rows * cols;
mem = new Xvar* [rows];
mem [0] = new Xvar [size];
for (i=1;i<rows;i++)
mem [i] = &mem [0][i*cols];
return mem;
}catch (...) { assert (...) }
}
I think, the second way is not recommended because, if the first new fails, mem is NULL,
so if we do mem [0] , we are accessing to a memory that is not allocated, so that application fails at that point, and error cannot be catched.
In the second way, if the first
newfails, then evaluation immediately jumps to the catch block and never even tries to accessmem[0].In any case, if you want to allow allocation to fail and detect this easily, you should probably use the
nothrowvariant, which simply returnsNULLif the allocation fails. So something like