why should `new` be used as little as possible In C++?

1 Like

There are 2 memory allocation techniques: static allocation and dynamic allocation. There are corresponding regions of memory for each: the stack and the heap respectively.

Two key reasons to use the heap:

You don't know how much memory you need at compile-time. For instance, when reading a text file into a string, you usually don't know what size the file has, so you can't decide how much memory to allocate until you run the program.

You want to allocate memory which will persist after leaving the current block. For instance, you may want to write a function string readfile(string path) that returns the contents of a file. In this case, even if the stack could hold the entire file contents, you could not return from a function and keep the allocated memory block.

use the stack as often as possible

faster to type;
faster when run;
less prone to memory/resource leaks.

the stack is fast and foolproof