Object
life cycle refers to the events that an object experiences including and between creation and destruction. Life cycle generally includes
memory management and operations after allocation and before deallocation. Object creation generally consists of
memory allocation and
initialization where initialization includes assigning values to fields and running initialization code. Object destruction generally consists of
finalization (a.k.a. cleanup) and
memory deallocation (a.k.a. free). These steps generally proceed in order as: allocate, initialize, finalize, deallocate. Based on programming context, these steps may be partially or fully automated, and some of the steps can be customized. The frequency of customization tends to vary by step and programming context. Initialization is the most commonly customized step. Finalization is common in languages with deterministic destruction, notably C++, but rare in garbage-collected languages. Allocation is rarely customized, and deallocation generally cannot be customized.
Creation The way to create objects varies across programming contexts. In some class-based languages, a
constructor handles initialization. Like other methods, a constructor can be
overloaded in order to support creating with different initial state.
Destruction Generally, an object is removed from memory after it is no longer needed. However, if there is sufficient memory or a program has a short run time, object destruction may not occur, memory simply being deallocated at process termination. In some cases, object destruction consists solely of deallocating memory, particularly with garbage-collection, or if the object is a
plain old data structure. In other cases, cleanup is performed prior to deallocation, particularly destroying member objects (in manual memory management), or deleting references from the object to other objects to decrement reference counts (in reference counting). This may be automatic, or a special destruction method may be called on the object. In class-based languages with deterministic object lifetime, notably C++, a
destructor is called when an instance is deleted, before the memory is deallocated. In C++, destructors differ from constructors in various ways. They cannot be overloaded, must have no arguments, need not maintain
class invariants, and can cause program termination if they throw exceptions. With
garbage collection, objects may be destroyed when they can no longer be accessed by the program. The garbage-collector calls a
finalizer before memory deallocation. Destroying an object will cause any references to the object to become invalid. With manual memory management, any existing reference becomes a
dangling reference. With garbage collection, objects are only destroyed when there are no references to them. ==Consistency==