Your decisions about memory management will be strongly influenced by your earlier decisions on language and operating system, and you should detail such decisions in you architecture guidelines document, discussed in Chapter 4. C++ provides a versatile and customizable memory environment. The three principal areas of memory of concern to the application developer are
You can think of global memory as being initialized before
runs and being destroyed after main()
. Local variables are destroyed at the end of the block in which they are defined. You cannot explicitly delete a local variable, but the compiler destroys it for you when the object goes out of scope. Objects on the heap are created by a call to exit()
and destroyed by a call to new
. delete
In C++, memory management is the responsibility of the application programmer. C++ has no garbage collection. If you create an object on the heap, and then lose the pointer without deleting the object, that memory is lost to the system. We call that a memory leak, because it is as if the memory leaked away. Over time, memory leaks will bring your system to its knees.
It is possible, though difficult, to write a system without putting objects on the heap. You can declare all your objects on the stack, and aggregate objects only by value, thus avoiding the use of pointers altogether. This can be terribly inefficient, however, as passing by value is very expensive at run time.
Several idioms have been developed for C++ to make it easier and safer to work with dynamic memory. These include:
auto_ptrs