Wow... amazing insight Joe man. You rule....!
Using CArray certainly looks like a better idea... I'll look into it.
"Joseph M. Newcomer" <newcomer@flounder.com> wrote in message
No. It will probably fail in some fairly fascinating ways.
Fortunately, in the debug
version, if new throws a CMemoryException it will crash nicely
trying to delete the object
at 0xCCCCCCCC. You would have to write
int * p = NULL;
Note that there is no need to call delete because if the allocation
succeeded, the
exception isn't taken, and if the exception is taken, the value of p
is not defined unless
you've done the above line, in which case the corresponding line in
your catch handler is
unnecessary.
int * p = NULL;
try {
p = new int[10];
}
catch(CMemoryException * emex)
{
emex->Delete();
}
presumably after this point you are checking to see if p is
non-NULL.
Note that this requires that eventually you need to delete the array
of ints. This is
dangerous, in that you could do something that bypasses the
deallocation. I prefer to
write
CArray<int, int>p;
p.SetSize(10);
(Note that you would need to add a try/catch around the SetSize).
This way, when the
array goes out of scope, the storage is automatically freed. If you
need an int *, you
can just do p.GetData(), which returns you an int * to the actual
int array.
Alternatively, you could use std::vector.
joe
On Tue, 30 May 2006 03:48:05 +0500, "Adeel" <dontWantSpam@All>
wrote:
Hello,
I was wondering what is the usual practice for exception handling
with
the new operator.
For example...,
<code>
int *p;
try {
p = new int[10];
}
catch (EMemoryException *emex) {
delete [] p;
p = NULL;
emex->Delete;
}
</code>
Would this piece of code work with all sorts of memory allocation
errors and ensure a safe way of using the dynamically allocated
memory?
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm