object lifetime in c c++
DESCRIPTION
Object Lifetime is critical for understanding C++TRANSCRIPT
February 28, 2009
Object Lifetime in C/C++
Madhubanti DasguptaInterra Systems (India) Pvt. Ltd.
Current Practices in Object Oriented Software Development
Meghnad Saha Institute of Technology
04/12/23 22
Agenda
• Object Lifetime Fundamentals
• Data Memory Areas
• Types of Objects– Static Objects– Automatic Objects– Dynamic Objects
04/12/23 33
Object Lifetime Fundamentals
Allocation - DeallocationAllocation - Deallocation
04/12/23 44
Object Lifetime Fundamentals
• Starts with Constructor execution – As soon as Initialization ends and control enters
Constructor Body – Must follow Memory Allocation
• Ends with Destructor execution– As soon as control leaves Destructor Body– Must precede Memory De-allocation
04/12/23 55
Object Lifetime Fundamentals
class MyClass;
void MyFunc() // Allocation on Stack for myObj{
MyClass myObj; // Construction// MyClass::MyClass()
...myObj.myMethod(); // Use...return; // Destruction - Implicit
// myObj.~MyClass()} // De-Allocation from Stack for myObj
04/12/23 66
Object Lifetime Fundamentals
• Stages– Memory Allocation & Binding– Constructor Call & Execution– Object Use– Destructor Call & Execution– Memory De-Allocation & De-Binding
Managed LifetimeManaged Lifetime
04/12/23 77
Object Lifetime Fundamentals
• Built-in / Pre-Defined Types– No Explicit Constructor / Destructor– Compiler optimizes these calls– Same pattern for the Creation / Destruction
processes
04/12/23 88
Data Memory Areas
System Agnostic ViewSystem Agnostic View
04/12/23 99
Data Memory Areas
Area DataConst Data Constant literals including strings
Text Program Code
Stack Automatic Objects
Free Store & Heap
Dynamic Objects managed by new / delete & malloc / free
Static Global / File Scope Objects;
Static Class Scope Objects;
Function Scope Objects
04/12/23 1010
Types of Objects
Static – Automatic – Dynamic Static – Automatic – Dynamic
04/12/23 1111
Static Objects
Compiler-Managed Objects in the Global StoreCompiler-Managed Objects in the Global Store
04/12/23 1212
Static Objects
• Objects in Static Memory• Constructed only once at Program Startup
– Function Objects created on first execution
• Destructed on Normal Program Termination– return or exit()– Uses atexit() Registration to call Destructors
• Static Objects are– Global and Namespace Objects– Class Objects with the static modifier– Function Objects with the static modifier
• Memory requirements handled by the compiler– Offsets / Layout statically computed
04/12/23 1313
Static Objects
static MyClass obj1; // Global static objectMyClass MyClass::obj2; // Class static object
void staticFunc(){
static MyClass obj3; // Function static object{
static MyClass obj4; // Block static object}
}
04/12/23 1414
Static Objects
• Global (or File) / Namespace Scope / Class Scope– Built-in Types
• Has no boundary for translation units – literally “load time”• Object created (& initialized) implicitly at program load
– before first assembly instruction in the program– actually before any global object of user-defined type is constructed
• Object destroyed implicitly before the program unload– after last assembly instruction in main()– actually after all global objects of user-defined type are destructed
– User-Defined Types• Space allocation is done at “load-time”• Object created (and initialized)
– sequentially within a translation unit– arbitrarily across translation units
• Objects destroyed in the reverse order of creations
04/12/23 1515
Static Objects• Local Function / Block Scope
– Built-in Types• Same as static objects in Global Scope
– User-Defined Types• Space allocation is done at “load-time”• Object created (and initialized) when the control
passes the definition for the first time• Destroyed in the reverse order of creations (LIFO)
– after last assembly instruction in main()– before the global objects of user-defined type are destructed
• Uses atexit() – because the creation order is dynamic
04/12/23 1616
Execution beyond main()
static MyClass *obj; // Global Static Object Ptr
void clean() { delete obj; }// Wrapper Function
void staticFunc()
{
obj = new MyClass(); // Construction
atexit(clean); // atexit() Registration
}
04/12/23 1717
Execution beyond main()• atexit() signature
int atexit(void (*pFunction)(void));
• Register any function having the following signaturevoid CallbackFunction(void);
• Registered function called at runtime after main() exits• For Multiple Registrations, calls are made in the reverse
order of registration or LIFO• Used by
– Compiler for Local Static Objects– Application Programmer for any function call beyond main()
• return()or exit() invokes all Callbacks• abort() bypasses all Callbacks
04/12/23 1818
Automatic Objects
Compiler-Managed Objects in Local StoreCompiler-Managed Objects in Local Store
04/12/23 1919
Automatic Objects
• Objects in Stack (Local) Memory• Objects Managed via Static Scopes
– Function Scope– Block Scope within a Function Scope– Block Scope within another Block Scope
• Objects Laid out in the Stack Frame of the Function Scope– Constructed when the control passes the declaration – Destructed when (just after) the control leaves the scope
• Normal Exit: return / break / goto• Abnormal Exit: Exception (throw)
– Objects (within a scope) are destroyed in the reverse order of creations
• Memory requirements handled by the Compiler
04/12/23 2020
Automatic Objects
void automaticFunc(){
MyClass obj1; // Function ScopedMyClass *obj2 = new MyClass();
{ MyClass obj3; } // Block Scoped
if (MyClass obj4()) { delete obj2; } // if Scopedelse { }
}
04/12/23 2121
Automatic Objects
• Automatic Objects are– Function Scope Objects
• Formal Parameters• Return Values
– Block Scope Objects• Compound Statements (like ‘for’ or ‘switch’ or ‘while’ or ‘do-while’)
– Non-static Data Member Objects in a class• As part of the Parent Object’s Layout
– Base class Object in a class• As part of the Derived Object’s Layout
– Temporary Objects• Unnamed Objects• Compiler Generated & Managed
04/12/23 2222
Dynamic Objects
User-Managed Objects in the Free StoreUser-Managed Objects in the Free Store
04/12/23 2323
Dynamic Objects
• Objects in Free Store Memory• Memory allocated dynamically
– Constructor called by operator new / placement new• Must follow Memory Allocation
– Destructor called by operator delete• Must precede Memory De-allocation
– Lifetime controlled by the user• Transformed to scoped management by Smart Pointers
• Memory requirements handled by the User• Lifetime Managed by the User
04/12/23 2424
Dynamic Objectsvoid dynamicFunc(){
MyClass *obj = new MyClass(); // Dynamic Object
int offset = sizeof (MyClass);char *plBuf = new char [2 * offset]; // Allocation
MyClass *plObj1 = new (plBuf) MyClass(); // ConstructionMyClass *plObj2 = new (plBuf + offset) MyClass();
plObj1->~MyClass(); // DestructionplObj2->~MyClass();
delete [] plBuf; // Deallocation}// Dynamic Object ‘obj’ Leaks Memory
04/12/23 2525
Thank You