Re: catch exception
Juha Nieminen <nospam@thanks.invalid> wrote in news:t5Qrk.51$ME2.22
@read4.inet.fi:
Really? What will be the value of p if 'new' throws?
Wouldn't it be better like this:
A(): p(0)
{
try
{
p = new int;
}
catch(...)
{
delete p;
}
}
It depends upon what you are after, In the previous case, if new
throws, p is never assigned a value and A is never constructed. If all
of your resources are wrapped in RAII classes (such as auto_ptr), then
anything constructed prior to the new throwing will be cleaned up as the
exception leaves A's constructor. This is all done for you. The code
you provided really doesn't do anything. If the new throws, then p
won't need deleted. If the new works, then it won't be deleted. If you
didn't want the new to prevent the construction of A, then you could do
something like:
A()
{
try
{
std::auto_ptr<int> p(new int);
//do stuff with p
// p gets automatically deleted as it leaves this scope.
} catch(...)
{ // don't really care if the above worked or not
}
// do other stuff
}
-or-
A()
{
try
{
p.reset(new int);
//do stuff with p
// p gets automatically deleted when A gets deleted.
} catch(...)
{ // don't really care if the above worked or not
}
// do other stuff
std::auto_ptr<int> p;
}
Both of these would prevent the allocation of p from preventing the
construction of A (though if you are really that low on memory, do you
really want to carry on?) and will automatically handle the deletion of
the object when A is destroyed.
Generally speaking (meaning there are always special cases) I think
Andre's solution is the cleanest for most uses.
joe