Re: Stack vs. Heap
- From: Joseph M. Newcomer <newcomer@xxxxxxxxxxxx>
- Date: Thu, 10 Jan 2008 10:36:38 -0500
Typically, if an element does not need to exist beyond the scope of its variable, you are
much better off allocating it on the stack instead of the heap. Objects which need to
have a lifetime beyond the local scope must be allocated on the heap. It is common to
allocate objects whose size is not known at compile time on the heap, although in this
case the preferred method depends on the lifetime; for values needed within the local
scope, CArray or std::vector are a better choice than a raw malloc or new because the
destructors of these objects ensure that the object is properly deallocated when you leave
scope.
An example of poor strategy:
CMyDIalog * dlg = new CMyDialog;
dlg->DoModal();
...
delete dlg;
the corresponding good strategy is
CMyDialog dlg;
dlg.DoModal();
...
A poor strategy
LPBYTE b = new BYTE[size];
...
delete b;
A good strategy
CByteArray b;
b.SetSize(size);
or
std::vector<BYTE> b;
b.resize(size);
A poor strategy
LPDWORD d = new DWORD;
*d = 0;
SomeAPI(d);
...
delete d;
A good strategy
DWORD d = 0;
SomeAPI(&d);
...
A failing strategy
TCHAR buffer[COMPILE_TIME_SIZE];
read_stuff_into(buffer);
PostMessage(UWM_HERES_DATA, (WPARAM)buffer);
A working strategy
TCHAR * buffer = new TCHAR[COMPILE_TIME_SIZE];
read_stuff_into(buffer);
PostMessage(UWM_HERES_DATA, (WPARAM)buffer);
where the OnHeresData handler does a delete of the TCHAR pointer passed via WPARAM:
LRESULT CMyClass::OnHeresData(WPARAM wParam, LPARAM)
{
TCHAR * buffer = (TCHAR *)wParam;
... use it
delete buffer;
return 0;
}
The above case shows that the object needs to exist beyond the scope of the function in
which it is declared.
Bottom line: if you don't need to put it on the heap, don't put it on the heap. If you
need to put it on the heap (as CArray and std::vector do for their contents) avoid
situations in which an explicit delete is required. If you need it to exist for a long
time, put it on the heap.
joe
On Thu, 10 Jan 2008 11:30:31 +0200, "Dan" <dan@xxxxxxxxx> wrote:
Is there a simple rule when to define objects on the heap and when to do itJoseph M. Newcomer [MVP]
on the stack?
Regards
Dan
email: newcomer@xxxxxxxxxxxx
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
.
- References:
- Stack vs. Heap
- From: Dan
- Stack vs. Heap
- Prev by Date: Re: Get the handle of controls not reachable with the mouse
- Next by Date: Re: Using sprintf_s in VC++ 6.0
- Previous by thread: Re: Stack vs. Heap
- Next by thread: Html control embedded
- Index(es):
Relevant Pages
|