What is the design factor in managing memory in C++?
For example: why is there a memory leak when a program does not release a memory object before it exits? Isn’t a good programming language design supposed to maintain a “foo-table” that takes care of this situation ? I know I am being a bit naive, but what is the design philosophy of memory management in C++ with respect to classes, structs, methods, interfaces, abstract classes?
Certainly one cannot humanely remember every spec of C++. What is the core driving design of memory management?
In almost all cases, you should use automatic resource management. Basically:
Rarely do you have to write your own RAII container: the C++ standard library provides a whole set of containers (e.g.,
vectorandmap) and smart pointers likeshared_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
deleteyourself1 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.