Why should C++ programmers minimize use of 'new'?

C++Server Side ProgrammingProgramming

new is used for dynamic memory allocation. The memory allocated in this case goes on the heap. There are several costs associated with this type of memory allocation along with the programmer having to do manual memory cleaning and management. This type of allocation must be used when −

  •  You don't know how much memory you need at compile time.
  • You want to allocate memory which will persist after leaving the current block.

Other than these, there are very few cases where dynamic memory allocation is required. This is because, in C++, there is the concept of a destructor. This function gets called when an object's/resource's lifetime ends. This can be used to free the memory. So when you create an object that has its own objects, and the main object goes out of scope, it frees the memory of its child objects as well.

These variables are called automatic variables and this type of memory usage automatic storage. You should use it because it is faster to type, faster when run and less prone to memory/resource leaks.


raja
Published on 28-Feb-2018 16:10:19
Advertisements