[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppSingleton
This version of a Singleton uses new without delete. This results in a memory leak. However, this leak does not increase in size and in the end of the program is removed automatically. The Singleton's destructor is not called in this process. You
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppSingleton
(C++) Singleton
A Design Pattern [1] ensuring that the Singleton class has only one instance. This can be used for e.g.C++ Singleton
Common for all Singletons is:- Contructor is private or protected
- Destructor is private or protected
- The instance of the Singleton is a static member variable
- The method to get a pointer to this instance is static.
Example from [1]
class Singleton { public: static Singleton* instance() { if (mpInstance==0) mpInstance = new Singleton(); return mpInstance; } protected: Singleton() {} private: static Singleton* mpInstance; }; Singleton* Singleton::mpInstance=0; Singleton* myGlobal1 = Singleton::instance(); Singleton* myGlobal2 = Singleton::instance(); assert(myGlobal1==myGlobal2);
- include <cassert>
This version of a Singleton uses new without delete. This results in a memory leak. However, this leak does not increase in size and in the end of the program is removed automatically. The Singleton's destructor is not called in this process. You
Improved example
When you make use of an std::auto_ptr, the destructor will get called.class Singleton { public: static Singleton* instance() { assert(mpInstance.get()!=0); return mpInstance.get(); } private: friend std::auto_ptr<Singleton>; Singleton() {}; ~Singleton() {}; const static std::auto_ptr<Singleton> mpInstance; }; const std::auto_ptr<Singleton> Singleton::mpInstance(new Singleton); int main() { Singleton * r = Singleton::instance(); Singleton * s = Singleton::instance(); assert(r==s); }
- include <cassert>
- include <memory>
Code links
Singleton in other programming languages
- (none on CodePedia yet)
References
1) Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides. Design Patterns. Publisher: Addison-Wesley Professional; 1st edition (January 15, 1995). ISBN: 0201633612[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
