Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Unlike Java, C++ has no garbage collection. Garbage collection is a thread that recovers heap memory that is no longer referenced. It runs when the CPU is relatively idle or when it is running out of memory. When an object is no longer referenced, it is deleted, and the memory that it occupied is made available for use by other objects. It has the benefit of being less work for the developer, who does not need to worry about memory leaks,[4] but it is certainly more work for the CPU.
[4] Actually, Java developers do worry and often try many tricks to create fewer heap objects. They also have ways to force the garbage collector to run more frequently (and, of course, consume more CPU cycles).
The next examples show a way of building garbage collection into the design of a class by means of reference counting. Reference counting is an example of resource sharing. It is considered much more efficient, in terms of both developer and CPU time, than depending on a garbage collector to manage the heap.