Those who program with modern languages like C# or Java has a tendency to use each and every object declaration in C++ with new. Why we should avoid using new as much as possible?
- Unlike Java/C#, C++ doesn’t employ any memory manager by its own to control the life time of dynamically allocated objects (using new).
- C++ using operating system routines to allocate the memory and too much new/delete could fragment the available memory. The architecture and management of a garbage collector is entirely different from a native perspective.
- Improper memory management could lead memory leaks and it’s really hard to track.
- The stack objects implementation is foolproof.
- With any application, if large chunk of memory is frequently being used, it’s advised to pre-allocate it and release when not required.
- The downside of using stack objects are, it creates intermediate copies of objects on returning, passing to functions (by value) etc. But the memory management of C#/Java helps the (JIT)compiler to manage these tasks memory efficient. However modern C++ compilers are well aware of these situations and they’ve optimized for performance.
- It’s really tedious in C++ if the memory being allocated and released in two different places. The responsibility for release is always a question and mostly we rely on some commonly accessible pointers, stack objects (maximum possible) and techniques like auto_ptr, shared_ptr (reference counted pointers – C++0x) (RAII objects)
- The best thing in C++ is that, you’ve control over the memory and the worst thing is that you will not have any control over the memory if we employ an improper memory management for the application. The crashes caused due to memory corruptions are the nastiest one in the world.