We Recommend

C++ The Core Language C++ The Core Language
C++: The Core Language is for C programmers transitioning to C++. It's designed to get readers up to speed quickly by covering an essential subset of the language. The subset consists of features without which it's just not C++, and a handful of others that make it a reasonably useful language.


Posted By

yuconner on 08/04/06


Tagged

patterns design


Versions (?)


Who likes this?

3 people have marked this snippet as a favorite

yuconner
copyleft
yarvin


Singleton class model


Published in: C++ 


Singleton class model then: SingletonClass *pSC = SingletonClass::getsingletoninstance(); pSC->anypublicfunction(); or: SingletonClass::getsingletoninstance()->anypublicfunction();

  1. //.h
  2. class SingletonClass {
  3.  
  4. static SingletonClass *singleton;
  5. SingletonClass();
  6.  
  7. public:
  8. static SingletonClass * get_singleton_instance();
  9. ~SingletonClass();
  10. };
  11.  
  12.  
  13. //.cpp
  14. SingletonClass *SingletonClass::singleton = NULL;
  15.  
  16. SingletonClass * SingletonClass::get_singleton() {
  17. if( singleton == NULL ) singleton = new SingletonClass();
  18. return singleton;
  19. }
  20.  
  21. SingletonClass::SingletonClass() {
  22. singleton = this;
  23. }
  24.  
  25. SingletonClass::~SingletonClass() {
  26. }

Report this snippet 

Comments

RSS Icon Subscribe to comments
Posted By: sudarkoff on January 24, 2007

Seeing how this is a "Popular" code snippet, I wanted to warn everybody, that it is not good for multithreaded environment. For more details: http://www.aristeia.com/Papers/DDJJulAug2004revised.pdf

Posted By: neoguru on October 31, 2007

Yo may find usefull information about Singleton here: http://sourcemaking.com/design_patterns/singleton

You need to login to post a comment.