SlideShare a Scribd company logo
February 28, 2009 Object Lifetime in C/C++ Madhubanti Dasgupta Interra Systems (India) Pvt. Ltd.   Current Practices in Object Oriented Software Development   Meghnad Saha Institute of Technology
Agenda Object Lifetime Fundamentals Data Memory Areas Types of Objects Static Objects Automatic Objects Dynamic Objects
Object Lifetime Fundamentals Allocation - Deallocation
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
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
Object Lifetime Fundamentals Stages Memory Allocation & Binding Constructor Call & Execution Object Use Destructor Call & Execution Memory De-Allocation & De-Binding Managed Lifetime
Object Lifetime Fundamentals Built-in / Pre-Defined Types No Explicit Constructor / Destructor Compiler optimizes these calls Same pattern for the Creation / Destruction processes
Data Memory Areas System Agnostic View
Data Memory Areas Program Code Text Global / File Scope Objects;  Static Class Scope Objects; Function Scope Objects Static Dynamic Objects managed by new / delete & malloc / free Free Store & Heap Automatic Objects Stack Constant literals including strings Const Data Data Area
Types of Objects Static – Automatic – Dynamic
Static Objects Compiler-Managed Objects in the Global Store
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
Static Objects static MyClass obj1;  // Global static object MyClass MyClass::obj2;  // Class static object   void staticFunc() { static MyClass obj3;  // Function static object { static MyClass obj4;  // Block static object } }
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
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
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 }
Execution beyond  main() atexit()  signature int atexit(void (*pFunction)(void));  Register any function having the following signature void 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
Automatic Objects Compiler-Managed Objects in Local Store
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
Automatic Objects void automaticFunc() { MyClass obj1; // Function Scoped MyClass *obj2 = new MyClass(); { MyClass obj3; } // Block Scoped if (MyClass obj4()) { delete obj2; }  // if Scoped else  { } }
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
Dynamic Objects User-Managed Objects in the Free Store
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
Dynamic Objects void dynamicFunc() { MyClass *obj = new MyClass(); // Dynamic Object int offset = sizeof (MyClass); char *plBuf = new char [2 * offset]; // Allocation MyClass *plObj1 = new (plBuf) MyClass();  // Construction MyClass *plObj2 = new (plBuf + offset) MyClass(); plObj1->~MyClass();   // Destruction plObj2->~MyClass(); delete [] plBuf;   // Deallocation } // Dynamic Object ‘obj’ Leaks Memory
Thank You

More Related Content

PPT
Serialization/deserialization
Young Alista
 
PDF
Serialization & De-serialization in Java
InnovationM
 
DOC
Serialization in .NET
Abhi Arya
 
PPT
Java Serialization
jeslie
 
PDF
Why using finalizers is a bad idea
PVS-Studio
 
PDF
Loaders (and why we should use them)
Michael Pustovit
 
PPTX
Singleton design pattern
anshu_atri
 
PDF
Angular Advanced Workshop (+ Challenges)
Georgios Kaleadis
 
Serialization/deserialization
Young Alista
 
Serialization & De-serialization in Java
InnovationM
 
Serialization in .NET
Abhi Arya
 
Java Serialization
jeslie
 
Why using finalizers is a bad idea
PVS-Studio
 
Loaders (and why we should use them)
Michael Pustovit
 
Singleton design pattern
anshu_atri
 
Angular Advanced Workshop (+ Challenges)
Georgios Kaleadis
 

What's hot (19)

PDF
JavaFX Dependency Injection with FxContainer
Srikanth Shenoy
 
PPTX
Java GC
Ray Cheng
 
PPTX
06.1 .Net memory management
Victor Matyushevskyy
 
KEY
Grand Central Dispatch Design Patterns
Robert Brown
 
PPTX
Qt test framework
ICS
 
PPT
My first experience with lambda expressions in java
Scheidt & Bachmann
 
PPTX
Iterator - a powerful but underappreciated design pattern
Nitin Bhide
 
PDF
Streams, Streams Everywhere! An Introduction to Rx
Andrzej Sitek
 
PPT
iOS Multithreading
Richa Jain
 
PPT
9781305078444 ppt ch10
Terry Yoast
 
PPTX
Effective java - concurrency
feng lee
 
PDF
Keeping track of state in asynchronous callbacks
Paul Houle
 
PDF
Iterator
melbournepatterns
 
PDF
Multithreading and Parallelism on iOS [MobOS 2013]
Kuba Břečka
 
PDF
Angular Optimization Web Performance Meetup
David Barreto
 
PDF
Concurrency Utilities in Java 8
Martin Toshev
 
PDF
Java Concurrency in Practice
Alina Dolgikh
 
PDF
Java Concurrency Gotchas
Alex Miller
 
KEY
Threading in iOS / Cocoa Touch
mobiledeveloperpl
 
JavaFX Dependency Injection with FxContainer
Srikanth Shenoy
 
Java GC
Ray Cheng
 
06.1 .Net memory management
Victor Matyushevskyy
 
Grand Central Dispatch Design Patterns
Robert Brown
 
Qt test framework
ICS
 
My first experience with lambda expressions in java
Scheidt & Bachmann
 
Iterator - a powerful but underappreciated design pattern
Nitin Bhide
 
Streams, Streams Everywhere! An Introduction to Rx
Andrzej Sitek
 
iOS Multithreading
Richa Jain
 
9781305078444 ppt ch10
Terry Yoast
 
Effective java - concurrency
feng lee
 
Keeping track of state in asynchronous callbacks
Paul Houle
 
Multithreading and Parallelism on iOS [MobOS 2013]
Kuba Břečka
 
Angular Optimization Web Performance Meetup
David Barreto
 
Concurrency Utilities in Java 8
Martin Toshev
 
Java Concurrency in Practice
Alina Dolgikh
 
Java Concurrency Gotchas
Alex Miller
 
Threading in iOS / Cocoa Touch
mobiledeveloperpl
 
Ad

Similar to Object Lifetime In C C++ (20)

PPTX
Dynamic memory allocation in c++
Tech_MX
 
PPT
C++tutorial
dips17
 
DOCX
Memory management in c++
Syed Hassan Kazmi
 
PDF
Memory management in C++
Ilio Catallo
 
PPT
Memory Management In C++
ShriKant Vashishtha
 
PDF
(3) cpp abstractions more_on_user_defined_types
Nico Ludwig
 
PPT
memory
teach4uin
 
PDF
00-intro-to-classes.pdf
TamiratDejene1
 
PPTX
Data structure and Algorithms (C++).pptx
ammarasalmanqureshi7
 
PPT
C/C++ Pointers explanationwith different examples
ulhaq18
 
PPT
Pointers_in_c.pptfffgfggdggffffrreeeggttr
MorfaSafi
 
PPT
Singleton Object Management
ppd1961
 
PDF
Dynamics allocation
Kumar
 
PPT
Pointers (Pp Tminimizer)
tech4us
 
PDF
Memory Management with Java and C++
Mohammad Shaker
 
PPT
Lecture2.ppt
Sabaunnisa3
 
PPT
Link list
Malainine Zaid
 
PPTX
iii-ii cd nCompiler design UNIT-V-1.pptx
nandan543979
 
PPT
Pointers
sanya6900
 
Dynamic memory allocation in c++
Tech_MX
 
C++tutorial
dips17
 
Memory management in c++
Syed Hassan Kazmi
 
Memory management in C++
Ilio Catallo
 
Memory Management In C++
ShriKant Vashishtha
 
(3) cpp abstractions more_on_user_defined_types
Nico Ludwig
 
memory
teach4uin
 
00-intro-to-classes.pdf
TamiratDejene1
 
Data structure and Algorithms (C++).pptx
ammarasalmanqureshi7
 
C/C++ Pointers explanationwith different examples
ulhaq18
 
Pointers_in_c.pptfffgfggdggffffrreeeggttr
MorfaSafi
 
Singleton Object Management
ppd1961
 
Dynamics allocation
Kumar
 
Pointers (Pp Tminimizer)
tech4us
 
Memory Management with Java and C++
Mohammad Shaker
 
Lecture2.ppt
Sabaunnisa3
 
Link list
Malainine Zaid
 
iii-ii cd nCompiler design UNIT-V-1.pptx
nandan543979
 
Pointers
sanya6900
 
Ad

More from ppd1961 (20)

PDF
Land of Pyramids, Petra, and Prayers - Egypt, Jordan, and Israel Tour
ppd1961
 
PDF
Science & Culture Article with Editorial & Cover
ppd1961
 
PDF
NDL @ YOJANA
ppd1961
 
PPT
Unified Modeling Language (UML)
ppd1961
 
PPT
OOP in C++
ppd1961
 
PDF
Digital geometry - An introduction
ppd1961
 
PDF
Innovation in technology
ppd1961
 
PPTX
Kinectic vision looking deep into depth
ppd1961
 
PDF
C++11
ppd1961
 
DOC
Function Call Optimization
ppd1961
 
DOC
How To Define An Integer Constant In C
ppd1961
 
PPT
Stl Containers
ppd1961
 
PPT
Technical Documentation By Techies
ppd1961
 
PPT
Vlsi Education In India
ppd1961
 
PPT
Reconfigurable Computing
ppd1961
 
PPT
Women In Engineering Panel Discussion
ppd1961
 
PPT
Handling Exceptions In C & C++ [Part B] Ver 2
ppd1961
 
PPT
Handling Exceptions In C & C++[Part A]
ppd1961
 
PPT
Dimensions of Offshore Technology Services
ppd1961
 
PPT
Concepts In Object Oriented Programming Languages
ppd1961
 
Land of Pyramids, Petra, and Prayers - Egypt, Jordan, and Israel Tour
ppd1961
 
Science & Culture Article with Editorial & Cover
ppd1961
 
NDL @ YOJANA
ppd1961
 
Unified Modeling Language (UML)
ppd1961
 
OOP in C++
ppd1961
 
Digital geometry - An introduction
ppd1961
 
Innovation in technology
ppd1961
 
Kinectic vision looking deep into depth
ppd1961
 
C++11
ppd1961
 
Function Call Optimization
ppd1961
 
How To Define An Integer Constant In C
ppd1961
 
Stl Containers
ppd1961
 
Technical Documentation By Techies
ppd1961
 
Vlsi Education In India
ppd1961
 
Reconfigurable Computing
ppd1961
 
Women In Engineering Panel Discussion
ppd1961
 
Handling Exceptions In C & C++ [Part B] Ver 2
ppd1961
 
Handling Exceptions In C & C++[Part A]
ppd1961
 
Dimensions of Offshore Technology Services
ppd1961
 
Concepts In Object Oriented Programming Languages
ppd1961
 

Object Lifetime In C C++

  • 1. February 28, 2009 Object Lifetime in C/C++ Madhubanti Dasgupta Interra Systems (India) Pvt. Ltd. Current Practices in Object Oriented Software Development Meghnad Saha Institute of Technology
  • 2. Agenda Object Lifetime Fundamentals Data Memory Areas Types of Objects Static Objects Automatic Objects Dynamic Objects
  • 3. Object Lifetime Fundamentals Allocation - Deallocation
  • 4. 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
  • 5. 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
  • 6. Object Lifetime Fundamentals Stages Memory Allocation & Binding Constructor Call & Execution Object Use Destructor Call & Execution Memory De-Allocation & De-Binding Managed Lifetime
  • 7. Object Lifetime Fundamentals Built-in / Pre-Defined Types No Explicit Constructor / Destructor Compiler optimizes these calls Same pattern for the Creation / Destruction processes
  • 8. Data Memory Areas System Agnostic View
  • 9. Data Memory Areas Program Code Text Global / File Scope Objects; Static Class Scope Objects; Function Scope Objects Static Dynamic Objects managed by new / delete & malloc / free Free Store & Heap Automatic Objects Stack Constant literals including strings Const Data Data Area
  • 10. Types of Objects Static – Automatic – Dynamic
  • 11. Static Objects Compiler-Managed Objects in the Global Store
  • 12. 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
  • 13. Static Objects static MyClass obj1; // Global static object MyClass MyClass::obj2; // Class static object void staticFunc() { static MyClass obj3; // Function static object { static MyClass obj4; // Block static object } }
  • 14. 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
  • 15. 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
  • 16. 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 }
  • 17. Execution beyond main() atexit() signature int atexit(void (*pFunction)(void)); Register any function having the following signature void 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
  • 18. Automatic Objects Compiler-Managed Objects in Local Store
  • 19. 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
  • 20. Automatic Objects void automaticFunc() { MyClass obj1; // Function Scoped MyClass *obj2 = new MyClass(); { MyClass obj3; } // Block Scoped if (MyClass obj4()) { delete obj2; } // if Scoped else { } }
  • 21. 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
  • 22. Dynamic Objects User-Managed Objects in the Free Store
  • 23. 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
  • 24. Dynamic Objects void dynamicFunc() { MyClass *obj = new MyClass(); // Dynamic Object int offset = sizeof (MyClass); char *plBuf = new char [2 * offset]; // Allocation MyClass *plObj1 = new (plBuf) MyClass(); // Construction MyClass *plObj2 = new (plBuf + offset) MyClass(); plObj1->~MyClass(); // Destruction plObj2->~MyClass(); delete [] plBuf; // Deallocation } // Dynamic Object ‘obj’ Leaks Memory