Reputation: 101251
I'm just learning about dynamic memory allocation, but there is one thing i'd like to be explained.
One use for dynamic allocation is for dynamic sized arrays, and thats clear to me. Another use is for normal objects.
What is a situation one should use it? Is it because normally objects are pushed on the stack, and could be popped of?
And how do you recognise a situation you should use dynamic memory allocation?
Upvotes: 0
Views: 996
Reputation: 755457
Another issue for dynamic memory is lifetime. Dynamic memory (new, malloc, etc ...) lives on the heap. It will stay alive until it is explicitly deleted by a piece of code through the appropriate memory function. This is very useful for long lived objects.
Non dynamic memory, or the stack, has a very definite lifetime. The memory allocated on the stack will only be around while that method is executing. Once the method is finished the memory will be automatically reclaimed.
Upvotes: 7
Reputation: 6052
You need dynamic allocation when you don't know how many objects you'll need to allocate.
Upvotes: 0
Reputation: 1985
It's very common to not know how many items you have to deal with - they might come from a file or whatever. To store items which come from outside your program you need dynamic sized arrays.
PS: Be sure to use STL classes like std::vector, not "arrays".
Upvotes: 0