Download presentation
Presentation is loading. Please wait.
Published byElfreda McCoy Modified over 8 years ago
1
Singleton C ++ Design Patterns: Singleton in Detail Kutsyk Vasyl
2
Overview Overview Destruction of Singleton atexit() Dead Reference Problem Phoenix Singleton Destruction Management Singletons and Multithreading Double Checked Locking Pattern (DCLP) Single- and multithreaded On Single- and Multicores Conclusion
3
A quick look on Singleton A Singleton creates iteself when used the first time A Singelton destroys itself A Singelton is a kind of „improved global variable“ used for Lifetime – Management (Lazzy initialization+Destruction Management) Definition (GOF) A singleton ensures that a class only has one instance and provides a global point of access to it.
4
A quick look on Singleton
5
Singleton itself
6
The Meyers Singleton
7
Destruction of Singleton
8
atexit() you can also call it by hand provided by standart C Library registered functions are called during a programm‘s exit in a LIFO order (objects created first, are destroyed last) But: LIFO is not allways a good choice
9
The Dead Reference Problem Lets assume we use three Singletons (Keyboard, Display and Log) Log is for error reporting and only instantiated if an error occures Keyboard and Display report all errors in instantiating and destroying them If three Meyers Singleton are used, this can lead to undefined behaviour.
10
Keyboard is constructed first Display fails, sends an error and envokes the initialization of Log Application is about to exit local static objects are destroyed in reverse order Log destroyed first Now the destruction of Keyboard fails for some reasons undefined behaviour
11
Addressing that problem PhoenixSingleton 1
12
Addressing that problem PhoenixSingleton 2
13
PhoenixSingleton But used at the Log example whole log file is deleted every destruction – creation cycle So we need: Log to be destroyed after Keyboard and Display therefore a way to control lifetime of various Singletons
14
Destruction Management 1 To much code to show it all on slides But basic idea: ◦used kind of longevity: SetLongevity(&SomeSingleton, X); ◦where X is donates the lifetime. The greater X, the later the object will be destroyed. ◦ SetLongevity internal administrates a queue where the objects are ordered by X ◦ each time it is called it internal calls: std::atexit(AEFN);
15
Destruction Management 2
16
Summary Only way to controll the lifecycle management is: ◦ use the internal atexit() function ◦ make sure it will not delete objects that are needed by other ones ◦delete in an ordered way at program exit ◦If the object‘s information is not needed to be saved, you can alsouse a phoenix singleton
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.