parts/4.4.Lifetime.md

4.4 Object Lifetime

In principle, the lifetime of an object begins immediately after a constructor completes creating the object and ends immediately before a destructor is called. C++ distinguishes references from objects. A reference has a lifetime that begins immediately after it is initialized and ends when the scope containing it completes. If the lifetime of an object designated by a reference ends before the lifetime of the reference ends, the reference is dangling and further access to its referent is undefined behaviour.

The lifetime of an object relates to its storage. There are four types of storage durations: static - includes global and static variables; lifetime guaranteed to be the execution duration of main() (or the equivalent for freestanding implementations) thread - variables have a lifetime of no longer than the lifetime of the containing thread automatic - scope of declaration defines lifetime dynamic - storage for objects is acquired from dynamic memory allocation and its lifetime is manually controlled.

The lifetime of an object can be prematurely terminated by calling its destructor releasing or reusing its storage

Accessing an object outside of its lifetime is undefined behaviour.

Sharing a reference to an object can result in incorrect behaviours if an object is terminated using one reference and later accessed via another reference. A leak occurs when an object who’s lifetime has not ended but there are no more variables, pointers or references to that object.

TO Do: verify that this clause covers issues raised in: 6.11.PointerTypeConversion-HFC.md 6.13.NULLPointerDereference-XYH.md 6.14.DanglingReferenceToHeap-XYK.md 6.22.InitializationOfVariables-LAV.md 6.33.DanglingReferencesToStackFrames-DCM.md 6.38.DeepVsShallowCopying-YAN.md 6.39.MemoryLeakAndHeapFragmentation-XYL.md 6.61.ConcurrentDataAccess-CGX.md 6.63.ProtocolLockErrors-CGM.md 6.65.ModifyingConstants-UJO.md