C++ offers programmers a choice of allocating objects on the heap or on the stack.
Stack-based allocation is more efficient: allocation is cheaper, deallocation costs are truly zero, and the language provides assistance in demarcating object lifecycles, reducing the risk of forgetting to free the object.
On the other hand, in C++, you need to be very careful when publishing or sharing references to stack-based objects because stack-based objects are automatically freed when the stack frame is unwound, leading to dangling pointers.
With the new
operator, all objects are allocated on the heap in Java or C#.
Class1 obj = Class1();
Actually, the compiler would try to find a method called Class1()
.
E.g. the following is a common Java bug:
public class MyClass
{
//Oops, this has a return type, so its a method not a constructor!
//Because no constructor is defined, Java will add a default one.
//init() will not get called if you do new MyClass();
public void MyClass()
{
init();
}
public void init()
{
...
}
}
Note: "all objects are allocated on the heap" does not mean stack allocation is not used under the hood occasionally.
For instance, in Java, Hotspot optimization like escape analysis uses stack allocation.
This analysis performed by the runtime compiler can conclude for example that an object on the heap is referenced only locally in a method and no reference can escape from this scope. If so, Hotspot can apply runtime optimizations. It can allocate the object on the stack or in registers instead of on the heap.
Such optimization though is not always considered decisive...