Reputation: 707
Circle
is a class, with public method GetDiameter()
.
What is the difference between the following 2 sets of code?
Qn1: Does Method 1 allocates memory for c
on stack (hence no need free memory), while Method 2 allocates memory for c
on heap (need manually free memory)?
Qn2: When should we use Method 1 or Method 2?
Method 1:
void Init()
{
Circle c;
c.GetDiameter();
return;
}
Method 2:
void Init()
{
Circle *c = new Circle();
c->GetDiameter();
return;
}
Upvotes: 3
Views: 3556
Reputation: 8425
You haven't even began working with pointers and Method 2 has memory leak already.
Upvotes: 1
Reputation: 6342
Yes, Method 1 allocates on Stack and hence no need to free, where as Method 2 allocates on Heap which must be freed.
Upvotes: 3
Reputation: 28882
Stack
Heap
This means that for small object where only a short lifetime is ideal. The heap is needed for large objects or any object having a longer lifetime than the function in which is was created. The manual object lifetime does mean that you can develop memory leaks if you are not careful.
Upvotes: 0
Reputation: 7156
one of the best discussions on heap vs. stack I have seen is here: heap vs. stack (scroll down to the middle of the discussion)
short summary:
Upvotes: 2
Reputation: 3528
Method 1: Memory allocated on stack. Method 2: Memory allocated on heap. + As a general rule, if you use call 'new' you must call 'delete' to deallocate the memory.
Upvotes: 1
Reputation: 31435
Use method 2 when:
The latter techique is commonly used to handle polymorphism, so the type you get might not actually be the type of the pointer but a class derived from it.
Whenever you need to delete the return value, it is best to handle it by wrapping it in a smart pointer or some other object where its destruction will happen "automatically".
If there is clean-up to do at the end of the function this should ideally be done through the use of automatic objects (like scoped_ptr or auto_ptr). This ensures that the clean-up happens even if the function terminates early (eg an exception gets thrown). This technique is called RAII - Resource Acquisition Is Initialisation.
Upvotes: 6
Reputation: 6387
As a general rule for good coding practice, always use method 1 when possible. Method 2 should be used only if you need to store and/or share the pointer in different places. All objects used only locally in a method or class should be put in the stack.
Upvotes: 12