What is the core driving design of memory management ?
In almost all cases, you should use automatic resource management. Basically:
- Wherever it is practical to do so, prefer creating objects with automatic storage duration (that is, on the stack, or function-local)
- Whenever you must use dynamic allocation, use Scope-Bound Resource Management (SBRM; more commonly called Resource Acquisition is Initialization or RAII).
Rarely do you have to write your own RAII container: the C++ standard library provides a whole set of containers (e.g., vector
and map
) and smart pointers like shared_ptr
(from C++ TR1, C++0x, and Boost) work very well for most common situations.
Basically, in really good C++ code, you should never call delete
yourself1 to clean up memory that you've allocated: memory management and resource cleanup should always be encapsulated in a container of some kind.
1. Obviously, the exception here is when you implement an RAII container yourself, since that container must be responsible for cleaning up whatever it owns.