Re: Stack vs. Heap
"Dan" <firstname.lastname@example.org> ha scritto nel messaggio
Is there a simple rule when to define objects on the heap and when to do
on the stack?
When you define an object (class instance) on the stack, it is automatically
deleted (its destructor is called) when the class instance goes out of
Instead, when you allocate on the heap, you must pay attention to properly
cleanup the object (else you will have memory or resources leaks).
// ** Stack Allocation **
// Allocate MyClass instance on the stack
... use c
} // c destructor called by C++ compiler
// ** Heap Allocation **
// Allocate on the heap
MyClass * ptrC = new MyClass();
...use heap-allocated instance
} // Destructor *not* called here! Memory leak!
// Must do an explicit delete ptrC;
However, if you use smart pointers, like boost:: or tr1:: shared_ptr, you
can safely allocate on the heap, and let the smart pointer pay attention to
free the object it is referencing. (So, with shared_ptr, you can safely
allocate on the heap, and kind of "forget" about freeing the object. It's
kind of C# or Java garbage collection...)
Recently, Visual C++ Team released a kind of "Service Pack 0" for VS2008,
which includes the useful shared_ptr class, and also other great things. I
recall that David C. posted the link on this newsgroup recently. You can
read something also here:
In general, if you have a small objects, you can allocate on the stack.
Instead, if you want to allocate big memory, you should allocate on the heap
(the stack is a limited resource, more limited than the heap).
Note also that there are classes like C++ STL container classes (e.g.
std::vector) that you allocate on the stack. But the class implementation
internally can allocate the required memory on the heap, e.g.:
std::vector< double > someData(1000);
The vector class instance ('someData') is allocated on the stack (so you
don't have to call its destructor explicitly), but the vector data (the 1000
double values) is allocated on the heap internally by std::vector