In article <e7yi5BAxHHA.3340@TK2MSFTNGP04.phx.gbl>, Igor Tandetnik wrote:
From: "Igor Tandetnik" <itandetnik@mvps.org>
Subject: Re: try-catch destructor
Date: Wed, 11 Jul 2007 17:13:17 -0400
Newsgroups: microsoft.public.vc.language
LarryW <lwdaddio@newsgroups.nospam> wrote:
One of our developers wrote the following test program:
void CTest_TryCatchDlg::TestMemoryLeak()
{
try
{
Ctest *p = new CTest();
WillThrowException();
delete p;
}
catch(...)
{
OutputDebugString("Temp");
}
}
The CTest is just an empty object with a do-nothing constructor and
destructor. WillThrowException does just that. When we run it in the
debugger stepping into everything and with a break-point on the
destructor, it never gets called and the debugger reports a memory
leak (VS 6.0). It was my understanding that the try-catch mechanism
would unwind the stack and call the destructor for 'p' and that 'p'
is just on the stack and would go out of scope at the end of the
block.
p is a pointer, an object of built-in fundamental type. Pointers don't
have destructors. The object the pointer _points to_ does have a
destructor, but that object is not on the stack (it's on the heap).
If you believe otherwise, why did you write 'delete p;' at all? p goes
out of scope in any case, whether the exception is thrown or not. But
for some reason only in one of these cases you feel the need to delete
the pointed-to object explicitly.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925