Search code examples
c++constructorheap-memorydynamic-memory-allocationnew-operator

What is the use of creating objects on the free store?


void fun()
{
    A *a = new A;   //Here A is a class
}                   //a should be deleted in fun()'s scope

int main()
{
    fun();
    return 0;
}

The object created exists on the free store and cannot be used by the main() function. The why should the objects be created on the free store. Yes we can pass the object reference to the main function but we can even pass a copy of the object(even when not created using the new operator). Then what's the exact use of the new and delete operator?


Solution

  • In your example, there is none, and it isn't good practice to use dynamic allocation. Dynamic allocation is used when objects have identity (or cannot be copied for some other reason), and the lifetime of the object does not correspond to some pre-determined lifetime, like static or auto. Dynamic allocation may also be used in a few cases where copying is expensive, and the profiler shows that the copying is a bottleneck; in such cases, using dynamic allocation and copying a pointer may remove the bottleneck. (But this should never be done until profiling shows it necessary.)