[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppSingleton

(C++) Singleton

A Design Pattern [1] ensuring that the Singleton class has only one instance. This can be used for e.g.
  • To be sure all copies of this instance are the same.
  • To prevent the use of globals

C++ Singleton

Common for all Singletons is:

Example from [1]

  1. include <cassert>
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);


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.

  1. include <cassert>
  2. include <memory>
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); }


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

last edited (November 18, 2006) by bilderbikkel, Number of views: 5539, Current Rev: 14 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.