Re: C++ memory cleaning up rules
luking ha scritto:
I am new to MFC, I am wondering if it is good practice to clean up
memory everytime an object instance is created and no long used?
say,string allocation, class object? Any rules or examples ?
I want to capture a screen shot every 3 minutes, do I need to release
the memory ScreenCapture used in this case?
void CMonitor01Dlg::OnTimer(UINT nIDEvent)
{
ScreenCapture *sc;
sc=new ScreenCapture();
sc->CaptureScreen(L"C:\\Screen.jpg");
}
Thank you so much!
Yes, in general, as C++ rule, to every allocation on the heap made by
'new', it should correspond a symmetric cleanup using 'delete' (and if
you allocate arrays on the heap with 'new[]', you should call 'delete[]').
The C++ native heap is not "managed", like C#'s heap, so you should pay
attention to memory freeing, to avoid memory leaks.
You can make your code easier using smart pointers, like shared_ptr.
There is a free implementation available in Boost, or you can install
SP1 for VS2008 and get Microsoft's TR1 implementation of shared_ptr.
Another advantage of smart pointers is that they are "exception safe",
e.g. if something throws an exception (e.g. a call to new fails, or some
method of some C++ class throws...), smart pointers are properly cleaned up.
HTH,
Giovanni