Garbage Collector in C++?

Garbage Collector in C++?

A garbage collector is handy, since it eliminates a big source for bugs, runtime crashes and memory leaks. However, garbage collection is not for free; it incurs additional runtime overhead for repeated operations like compaction, reference counting, and memory initialization. Furthermore, when you use garbage collection, destructors are not necessarily invoked right after an object is destroyed, but at an indeterminate time afterwards. For these reasons, C++ does not provide a garbage collector. Nonetheless, there are techniques to minimize–and even eliminate–the perils and drudgery of manual memory management without the associated disadvantages of garbage collection.

The easiest way to ensure automatic memory allocation and deallocation is to use local objects. For objects that have to grow and shrink dynamically, you can use STL containers like vector and list that automatically and optimally adjust their size. In addition, the standard auto_ptr class template automatically releases heap memory when its function or block has exited. Finally, in order to create an object that exists throughout the execution of a program, you can declare it as static. These techniques make explicit heap allocation and deallocation rarely needed, if at all.


Share the Post: