SlideShare a Scribd company logo
November 7, 2005 Singleton Object Management Dr. Partha Pratim Das Interra Systems (India) Pvt. Ltd.   Resource Management Series
Agenda Backgrounder atexit() behavior Object Lifetime Singleton Class What?, Why? & How? A simple singleton  How to enforce singleton discipline Meyer’s Singleton The Dead Reference Problem The Phoenix Singleton Q&A
Backgrounder Object Lifetime
atexit()  Callback Behavior –  Execute code after  main() atexit()  signature int atexit(void (*pFunction)(void));  // 0 is success Use  atexit()  to register any function having the following signature void CallbackFunction(void); The registered function will be called from the runtime system after  main()  exits If multiple functions are registered, then the calls will made be in the reverse order of registration (LIFO) Used by: Compiler for  Local Static Objects Application Programmer for any function call beyond  main()
atexit()  Callback Behavior Note: Executing  return  from  main()  or direct call to  exit(.)  invokes all callbacks registered with  atexit()  before the control actually exits (global destructors are called).  Call to  abort()  bypasses callbacks. atexit()  registration from within a Callback function may have unspecified behavior.
Object Lifetime Starts with Constructor execution Must  follow  Memory Allocation Ends with Destructor execution Must  precede  Memory De-allocation For Built-in Types (w/o Constructor / Destructor) the notion follows the same pattern though the compiler actually optimizes the creation / destruction processes.
Object Lifetime Automatic Object – Function / Block Scope Space allocated on stack when (just before) the control enters the scope Object created (and initialized) when the control passes the declaration Object destroyed when (just after) the control leaves the scope Objects (within a scope) are destroyed in the reverse order of creations Space de-allocated after all automatic objects have been destructed.
Object Lifetime Non-static member Object – Class Scope Constructed in the initialization list of the Constructor of the Parent Object Before the first statement of the constructor executes Follows the lexical order of declarations in the class Destructed by the Destructor of the Parent Object After the last statement of the destructor executes
Object Lifetime Free Store Object Lifetime controlled by the user Constructor called by operator new Must follow Memory Allocation Destructor called by operator delete Must precede Memory De-allocation
Object Lifetime Static Object – Global / Class Scope Built-in Type – no constructor / destructor Object created (and initialized) implicitly when the program is loaded  before first assembly instruction in main() actually before any global object of user-defined type is constructed Object destroyed implicitly before the program is unloaded  after last assembly instruction in main() actually after all global objects of user-defined type are destructed Has no boundary for translation units – literally “load time” Has no executable code in  construction  /  destruction .
Object Lifetime Static Object – Global / Class Scope User-Defined Types Space allocation is done at “load-time”.  Allocated space is zero-filled Object created (and initialized) sequentially within a translation unit  Creation order between different translation units is arbitrary  Some iostreams objects are properly initialized for use by the static constructors. These control text streams – cin, cout, cerr, clog Destroyed in the reverse order of creations – creation order is static iostreams objects can be used within the destructors called for static objects, during program termination.
Object Lifetime Static Object – Function / Local Scope Built-in Type Same as static objects in Global / Class Scope User-Defined Types Object created (and initialized) when the control passes the declaration 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
Static Object Lifetime An Example
 
 
 
 
Output: VC 6.0
Output: VC 7.1
Singleton Objects What and Why
What is a Singleton Class? A class is a singleton if It has only one instance, and Global point of access to the singular instance Can be accessed anytime during the application “ Global point of access” – Implications  Singleton object “owns” itself No client step to create singletons Creates and Destroys itself. Singleton is a Design Pattern A singleton is an improved global variable
Lifetime Semantics for a Singleton A single object of a class stays throughout the lifetime of an application  Created when the execution of the program “starts” and remains there till the application “ends”  The Singleton class is instantiated at the time of first access and same instance is used thereafter till the application quits.  At no point during execution there is more than one instance of the class; but in between it may be created & destroyed several times. There are execution points where no object exists.
Singleton Examples The office of the President of India is a Singleton.  The constitution specifies the means by which a President is selected, limits the term of office, and defines the order of succession.  There can be  at most  one President at any given time. There will be  exactly  one at any given time. Regardless of the personal identity of the President, the title, “President of India" is a global point of access that identifies the person in the office.
Singleton Examples Purify license in a network can be a Singleton.  A Singleton connection objects can ensure that only one connection can be made at any time.  Printer can be a singleton in a network. Keyboard, Display, Log, … [MFC] – The global instance of the CWinApp-derived application class is the singleton.  In EDAObjects™  Memory Manager Message Handler  Command Line Processor
Singleton Implementation How
Static Data + Static Function != Singleton Wrap the Singleton object and function that uses the object within a class Make both static Keep the object private and the method public This is not a “good” singleton because  static methods cannot be virtual Initialization and Clean-up is difficult There is no unique point of access
Essence of Singleton Implementation To make a class singleton Make all constructors private Provide a static method as a unique access point for the singleton. Examples follow …
A Simple Singleton
A Simple Singleton A simple – no-frills singleton is illustrated Singleton is dynamically created  a static creation may cause conflict in creation order Does not have a proper destruction point Cannot  delete  from within  main()  since some global objects may be using it Hence the singleton leaks Is it a memory leak? Is it a resource leak?
Meyer’s Singleton – A Solution Create the singleton as a local static object Will be destroyed at exit Does it solve all problems? Singleton& Singleton::Instance()  { static Singleton theInstance; return theInstance; }
The Dead Reference Problem There are 3 singletons –  Keyboard,  Display and  Log Error Reporting Created on-demand All are implemented by Meyer’s Singleton Consider an exception scenario …
The Dead Reference Scenario Keyboard successfully created  Display fails to initialize Log created Error logged; application proceeds to  exit Log destroyed (LIFO order) Keyboard fails to shutdown Log::Instance() invoked for error reporting Returns a dead object!!!
The Dead Reference Detection Maintain a flag with every singleton that tells if the singleton is alive. If a dead reference is detected, an exceptions is raised. The code follows …
Meyer’s Singleton with Dead Reference Detection
Phoenix Singleton Like Phoenix bird, this singleton rises repeatedly from its ashes Outline Retrieve the Caracas (this a global allocation) Reincarnate the singleton Register a callback for destruction with  atexit()
Phoenix Singleton
More Singletons … Explicit Management of Lifetime with user-assigned priorities (Longevity Control) Singletons under multi-threading Singleton template Singletons in Java, C# and .NET
Singletons in C++ References & Credits
References: Books Modern C++ Design:  Generic Programming & Design Pattern Applied   by  Andrei Alexandrescu , Pearson Education 2001 Most of the material from “Implementing Singletons” chapter Exceptional C++ by  Herb Sutter   Discussion on Object Lifetime Effective C++ &  More Effective C++:  by  Scott Meyers Many items relating to Object lifetime & Meyer’s Singleton
References: Papers Object Lifetime Manager –  A Complementary Pattern for Controlling Object Creation and Destruction   by  David L. Levine and Christopher D. Gill Douglas C. Schmidt ,  Design Patterns in Communications , (Linda Rising, ed.), Cambridge University Press, 2000.
Credits / Acknowledgements Debabrata Singha, ATOS Origin  discussion on the “Object Lifetime Manager” paper. understanding the  atexit()  behavior
Thank You

More Related Content

PPT
Introduction to Design Patterns and Singleton
PPTX
Exception handling
PDF
Java exception handling
PPT
EasyMock for Java
PDF
Testdriven Development using JUnit and EasyMock
PPTX
Design Pattern - Singleton Pattern
PPTX
Singleton Pattern (Sole Object with Global Access)
PDF
Java object oriented programming - OOPS
Introduction to Design Patterns and Singleton
Exception handling
Java exception handling
EasyMock for Java
Testdriven Development using JUnit and EasyMock
Design Pattern - Singleton Pattern
Singleton Pattern (Sole Object with Global Access)
Java object oriented programming - OOPS

What's hot (13)

PPTX
Easy mock
PDF
Advanced java interview questions
ODP
Easymock Tutorial
PPTX
Singleton Design Pattern - Creation Pattern
PPTX
Exceptions in Java
PPS
Java Exception handling
PPTX
OCA Java SE 8 Exam Chapter 6 Exceptions
PPT
Types of exceptions
PDF
DIC To The Limit – deSymfonyDay, Barcelona 2014
PPT
Exception
PDF
Dependency Injection
PDF
Writing Android Libraries
PPTX
The Singleton Pattern Presentation
Easy mock
Advanced java interview questions
Easymock Tutorial
Singleton Design Pattern - Creation Pattern
Exceptions in Java
Java Exception handling
OCA Java SE 8 Exam Chapter 6 Exceptions
Types of exceptions
DIC To The Limit – deSymfonyDay, Barcelona 2014
Exception
Dependency Injection
Writing Android Libraries
The Singleton Pattern Presentation
Ad

Viewers also liked (14)

PPTX
PATTERNS04 - Structural Design Patterns
PPTX
Singleton class in Java
PPTX
Construction Management in Developing Countries, Lecture 8
PDF
Code & Cannoli - Domain Driven Design
PDF
Domain Driven Design Development Spring Portfolio
PPTX
Structural Design pattern - Adapter
PDF
003 obf600105 gpon ma5608 t basic operation and maintenance v8r15 issue1.02 (...
PPTX
A Practical Guide to Domain Driven Design: Presentation Slides
PPTX
Domain Driven Design 101
PPTX
Domain Driven Design using Laravel
PPTX
Introduction to Angularjs
PDF
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
PDF
Software Design Patterns. Part I :: Structural Patterns
PDF
Cfb boiler basic design, operation and maintenance
PATTERNS04 - Structural Design Patterns
Singleton class in Java
Construction Management in Developing Countries, Lecture 8
Code & Cannoli - Domain Driven Design
Domain Driven Design Development Spring Portfolio
Structural Design pattern - Adapter
003 obf600105 gpon ma5608 t basic operation and maintenance v8r15 issue1.02 (...
A Practical Guide to Domain Driven Design: Presentation Slides
Domain Driven Design 101
Domain Driven Design using Laravel
Introduction to Angularjs
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Software Design Patterns. Part I :: Structural Patterns
Cfb boiler basic design, operation and maintenance
Ad

Similar to Singleton Object Management (20)

PPT
Object Lifetime In C C++
PPT
Handling Exceptions In C & C++ [Part B] Ver 2
PDF
RAII and ScopeGuard
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
PPTX
Lecture 4.2 c++(comlete reference book)
PPTX
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
PPT
C++tutorial
DOCX
Memory management in c++
PPT
Classes & objects new
PPT
Booa8 Slide 04
PPT
C++ Interview Questions
PDF
Bt8901 objective oriented systems1
DOC
My c++
PPT
Singleton design pattern
PDF
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
PDF
(3) cpp abstractions more_on_user_defined_types
PDF
Memory Management with Java and C++
PPT
Object Oriented Programming Examples with explanation
PDF
Memory management in C++
Object Lifetime In C C++
Handling Exceptions In C & C++ [Part B] Ver 2
RAII and ScopeGuard
Object Oriented Programming (OOP) using C++ - Lecture 4
Lecture 4.2 c++(comlete reference book)
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
C++tutorial
Memory management in c++
Classes & objects new
Booa8 Slide 04
C++ Interview Questions
Bt8901 objective oriented systems1
My c++
Singleton design pattern
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
(3) cpp abstractions more_on_user_defined_types
Memory Management with Java and C++
Object Oriented Programming Examples with explanation
Memory management in C++

More from ppd1961 (20)

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

Recently uploaded (20)

PDF
Spectral efficient network and resource selection model in 5G networks
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Machine Learning_overview_presentation.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Cloud computing and distributed systems.
PPTX
MYSQL Presentation for SQL database connectivity
Spectral efficient network and resource selection model in 5G networks
The AUB Centre for AI in Media Proposal.docx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Review of recent advances in non-invasive hemoglobin estimation
Reach Out and Touch Someone: Haptics and Empathic Computing
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
gpt5_lecture_notes_comprehensive_20250812015547.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
NewMind AI Weekly Chronicles - August'25-Week II
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Machine Learning_overview_presentation.pptx
Encapsulation theory and applications.pdf
Machine learning based COVID-19 study performance prediction
A comparative analysis of optical character recognition models for extracting...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Cloud computing and distributed systems.
MYSQL Presentation for SQL database connectivity

Singleton Object Management

  • 1. November 7, 2005 Singleton Object Management Dr. Partha Pratim Das Interra Systems (India) Pvt. Ltd. Resource Management Series
  • 2. Agenda Backgrounder atexit() behavior Object Lifetime Singleton Class What?, Why? & How? A simple singleton How to enforce singleton discipline Meyer’s Singleton The Dead Reference Problem The Phoenix Singleton Q&A
  • 4. atexit() Callback Behavior – Execute code after main() atexit() signature int atexit(void (*pFunction)(void)); // 0 is success Use atexit() to register any function having the following signature void CallbackFunction(void); The registered function will be called from the runtime system after main() exits If multiple functions are registered, then the calls will made be in the reverse order of registration (LIFO) Used by: Compiler for Local Static Objects Application Programmer for any function call beyond main()
  • 5. atexit() Callback Behavior Note: Executing return from main() or direct call to exit(.) invokes all callbacks registered with atexit() before the control actually exits (global destructors are called). Call to abort() bypasses callbacks. atexit() registration from within a Callback function may have unspecified behavior.
  • 6. Object Lifetime Starts with Constructor execution Must follow Memory Allocation Ends with Destructor execution Must precede Memory De-allocation For Built-in Types (w/o Constructor / Destructor) the notion follows the same pattern though the compiler actually optimizes the creation / destruction processes.
  • 7. Object Lifetime Automatic Object – Function / Block Scope Space allocated on stack when (just before) the control enters the scope Object created (and initialized) when the control passes the declaration Object destroyed when (just after) the control leaves the scope Objects (within a scope) are destroyed in the reverse order of creations Space de-allocated after all automatic objects have been destructed.
  • 8. Object Lifetime Non-static member Object – Class Scope Constructed in the initialization list of the Constructor of the Parent Object Before the first statement of the constructor executes Follows the lexical order of declarations in the class Destructed by the Destructor of the Parent Object After the last statement of the destructor executes
  • 9. Object Lifetime Free Store Object Lifetime controlled by the user Constructor called by operator new Must follow Memory Allocation Destructor called by operator delete Must precede Memory De-allocation
  • 10. Object Lifetime Static Object – Global / Class Scope Built-in Type – no constructor / destructor Object created (and initialized) implicitly when the program is loaded before first assembly instruction in main() actually before any global object of user-defined type is constructed Object destroyed implicitly before the program is unloaded after last assembly instruction in main() actually after all global objects of user-defined type are destructed Has no boundary for translation units – literally “load time” Has no executable code in construction / destruction .
  • 11. Object Lifetime Static Object – Global / Class Scope User-Defined Types Space allocation is done at “load-time”. Allocated space is zero-filled Object created (and initialized) sequentially within a translation unit Creation order between different translation units is arbitrary Some iostreams objects are properly initialized for use by the static constructors. These control text streams – cin, cout, cerr, clog Destroyed in the reverse order of creations – creation order is static iostreams objects can be used within the destructors called for static objects, during program termination.
  • 12. Object Lifetime Static Object – Function / Local Scope Built-in Type Same as static objects in Global / Class Scope User-Defined Types Object created (and initialized) when the control passes the declaration 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
  • 14.  
  • 15.  
  • 16.  
  • 17.  
  • 21. What is a Singleton Class? A class is a singleton if It has only one instance, and Global point of access to the singular instance Can be accessed anytime during the application “ Global point of access” – Implications Singleton object “owns” itself No client step to create singletons Creates and Destroys itself. Singleton is a Design Pattern A singleton is an improved global variable
  • 22. Lifetime Semantics for a Singleton A single object of a class stays throughout the lifetime of an application Created when the execution of the program “starts” and remains there till the application “ends” The Singleton class is instantiated at the time of first access and same instance is used thereafter till the application quits. At no point during execution there is more than one instance of the class; but in between it may be created & destroyed several times. There are execution points where no object exists.
  • 23. Singleton Examples The office of the President of India is a Singleton. The constitution specifies the means by which a President is selected, limits the term of office, and defines the order of succession. There can be at most one President at any given time. There will be exactly one at any given time. Regardless of the personal identity of the President, the title, “President of India" is a global point of access that identifies the person in the office.
  • 24. Singleton Examples Purify license in a network can be a Singleton. A Singleton connection objects can ensure that only one connection can be made at any time. Printer can be a singleton in a network. Keyboard, Display, Log, … [MFC] – The global instance of the CWinApp-derived application class is the singleton. In EDAObjects™ Memory Manager Message Handler Command Line Processor
  • 26. Static Data + Static Function != Singleton Wrap the Singleton object and function that uses the object within a class Make both static Keep the object private and the method public This is not a “good” singleton because static methods cannot be virtual Initialization and Clean-up is difficult There is no unique point of access
  • 27. Essence of Singleton Implementation To make a class singleton Make all constructors private Provide a static method as a unique access point for the singleton. Examples follow …
  • 29. A Simple Singleton A simple – no-frills singleton is illustrated Singleton is dynamically created a static creation may cause conflict in creation order Does not have a proper destruction point Cannot delete from within main() since some global objects may be using it Hence the singleton leaks Is it a memory leak? Is it a resource leak?
  • 30. Meyer’s Singleton – A Solution Create the singleton as a local static object Will be destroyed at exit Does it solve all problems? Singleton& Singleton::Instance() { static Singleton theInstance; return theInstance; }
  • 31. The Dead Reference Problem There are 3 singletons – Keyboard, Display and Log Error Reporting Created on-demand All are implemented by Meyer’s Singleton Consider an exception scenario …
  • 32. The Dead Reference Scenario Keyboard successfully created Display fails to initialize Log created Error logged; application proceeds to exit Log destroyed (LIFO order) Keyboard fails to shutdown Log::Instance() invoked for error reporting Returns a dead object!!!
  • 33. The Dead Reference Detection Maintain a flag with every singleton that tells if the singleton is alive. If a dead reference is detected, an exceptions is raised. The code follows …
  • 34. Meyer’s Singleton with Dead Reference Detection
  • 35. Phoenix Singleton Like Phoenix bird, this singleton rises repeatedly from its ashes Outline Retrieve the Caracas (this a global allocation) Reincarnate the singleton Register a callback for destruction with atexit()
  • 37. More Singletons … Explicit Management of Lifetime with user-assigned priorities (Longevity Control) Singletons under multi-threading Singleton template Singletons in Java, C# and .NET
  • 38. Singletons in C++ References & Credits
  • 39. References: Books Modern C++ Design: Generic Programming & Design Pattern Applied by Andrei Alexandrescu , Pearson Education 2001 Most of the material from “Implementing Singletons” chapter Exceptional C++ by Herb Sutter Discussion on Object Lifetime Effective C++ & More Effective C++: by Scott Meyers Many items relating to Object lifetime & Meyer’s Singleton
  • 40. References: Papers Object Lifetime Manager – A Complementary Pattern for Controlling Object Creation and Destruction by David L. Levine and Christopher D. Gill Douglas C. Schmidt , Design Patterns in Communications , (Linda Rising, ed.), Cambridge University Press, 2000.
  • 41. Credits / Acknowledgements Debabrata Singha, ATOS Origin discussion on the “Object Lifetime Manager” paper. understanding the atexit() behavior