Variables declared in functions (without 'new') are put on the stack.
Variables dynamically allocated are put on the heap.
Aside from the not-having-to-delete thing.... without getting too much into it, here's a very simplistic tradeoff:
- There is more heap space, but it's generally slower to access
- There is less stack space, but it's generally faster to access
There are other weird things to know too, though. strings and vectors, for example. The classes themselves are very small, and internally they put their buffer on the heap. So even if you have a vector on the stack, the actual array data will be on the heap... so it's typically better to put vectors and strings on the stack.
Where it gets hairy is when you have a structure/class that has very large members:
1 2 3 4 5 6 7 8 9 10 11 12
|
struct Foo
{
int huge[100000];
};
int main()
{
Foo ouch[100]; // 100000 * 100 * sizeof(int) bytes on the stack!
// ouch!!
return 0;
}
| |
For something like that, because 'Foo' is so large, you're generally better off putting it on the heap.