Variable creation on heap or stack in C++
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;
}
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.
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.
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:
下一篇: 在C ++中堆或堆栈上的变量创建