Re: doubt related to 'new' in MFC
On Wed, 04 Jul 2007 22:23:47 -0700, Mishra <mt.vijay@gmail.com> wrote:
Hi All,
I have one doubt about garbage collection in MFC.
Allow me to allay all your doubts. There is no garbage collection in native
C++ programs, which is normally what someone is talking about when he uses
the term "MFC" in this way.
If we function like
Void Fun()
{
Int *var = new int;
}
Will MFC delete memory allocated in Fun() by new operator after
closing the application?
The OS will reclaim all memory and other resources such as file handles
when the application terminates. This is not "garbage collection", though.
Garbage collection is what the .NET CLR does to reclaim objects that are no
longer referenced. In C++, we have destructors, which allow objects to
clean up after themselves. For example, I might write your function like
this:
void fun()
{
std::auto_ptr<int> i(new int);
...
}
By holding the dynamically allocated int in an auto_ptr, I am assured that
it will be deleted when the auto_ptr i goes out of scope, whether it be
through a return statement, falling off the end of the function, or by
throwing an exception. This is better than garbage collection, because it
happens at a well-defined time, which means resources such as file handles
are released as soon as you're finished with them. This is worse than
garbage collection, because it happens at a well-defined time, which means
performance can suffer if it wouldn't have hurt to postpone reclaiming the
resources. It requires more care than garbage collection, because you have
to use classes such as auto_ptr to store your dynamically allocated int. It
requires less care than garbage collection, because you don't have to worry
about "disposal" vs. "finalization", which aren't separate concepts in C++.
--
Doug Harrison
Visual C++ MVP