3

Possible Duplicate:
Can any one provide me a sample of Singleton in c++?
C++ Singleton design pattern
C++ different singleton implementations

I need some example of Singleton in c++ class because i have never wrote such class. For an example in java I can declare d a static field which is private and it's initialize in the constructor and a method getInstance which is also static and return the already initialize field instance.

Thanks in advance.

Community
  • 1
  • 1
Jordan Borisov
  • 1,603
  • 6
  • 34
  • 69

2 Answers2

4
//.h
class MyClass
{
public:
    static MyClass &getInstance();

private:
    MyClass();
};

//.cpp
MyClass & getInstance()
{ 
    static MyClass instance;
    return instance;
}
Andrew
  • 24,218
  • 13
  • 61
  • 90
  • 1
    it works thanks and also @Roee Gavirel give the same answer – Jordan Borisov Jul 29 '12 at 11:07
  • Nice. I always use the `getInstance` with the `==null`. the use of the static member is simple yet smart. – Roee Gavirel Jul 29 '12 at 14:49
  • One potential problem with this is that the instance will be destructed at some unknown point in time, possibly causing an order of destruction problem. I use this solution if the singleton needs destruction, but the pointer solution if it doesn't (which is well over 90% of the time). – James Kanze Jul 29 '12 at 15:50
  • @JamesKanze can you expand on the *order of destruction* problem? – quamrana Jul 29 '12 at 17:16
  • @quamrana: an order for destructing static variables is not specified. So if you have 2 singletons for example it's not defined which one will be destructed first – Andrew Jul 29 '12 at 20:45
  • @quamrana It's the same as the order of initialization problem, in reverse. If you attempt to use a singleton in the destructor of a static object, you don't want it to have already been destructed. And the only way to ensure this, generally, is never to destruct it. – James Kanze Jul 30 '12 at 07:57
  • @JamesKanze @Andrew perhaps if a singleton (called A) which needs another (called B) should take a reference to it by calling the static `B::getInstance()` method in its own constructor (`A::A()`). This should define an order for both construction and destruction. – quamrana Jul 30 '12 at 12:37
2

Example:
logger.h:

#include <string>

class Logger{
public:
   static Logger* Instance();
   bool openLogFile(std::string logFile);
   void writeToLogFile();
   bool closeLogFile();

private:
   Logger(){};  // Private so that it can  not be called
   Logger(Logger const&){};             // copy constructor is private
   Logger& operator=(Logger const&){};  // assignment operator is private
   static Logger* m_pInstance;
};

logger.c:

#include "logger.h"

// Global static pointer used to ensure a single instance of the class.
Logger* Logger::m_pInstance = NULL; 

/** This function is called to create an instance of the class.
    Calling the constructor publicly is not allowed. The constructor
    is private and is only called by this Instance function.
*/

Logger* Logger::Instance()
{
   if (!m_pInstance)   // Only allow one instance of class to be generated.
      m_pInstance = new Logger;

   return m_pInstance;
}

bool Logger::openLogFile(std::string _logFile)
{
    //Your code..
}

more info in:

http://www.yolinux.com/TUTORIALS/C++Singleton.html

Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94
  • Linking to external resources is not a good idea. If that sites disappears then your answer will become useless to future readers. – Martin York Jul 29 '12 at 14:42
  • @LokiAstari - You right. I've fix it. – Roee Gavirel Jul 29 '12 at 14:44
  • And you need to find a way to `delete` that instance before program exits using `atexit(..)` or manually. I personally feel [Andrew's answer](http://stackoverflow.com/a/11708673/227884) is cleaner. – UltraInstinct Jul 29 '12 at 14:52
  • Now that it is here. That is a not a good singleton. No concept of ownership. Thus no way of knowing when to delete it, nor is destruction automatic. Also because you are returning a pointer you are forcing the user to check for null. – Martin York Jul 29 '12 at 14:56
  • 1
    @Thrustmaster Generally, you _don't_ want to delete a singleton. You're using it to solve order of initialization problems; deleting it will introduce order of destruction problems. (There are exceptions, of course, where you have to delete it.) – James Kanze Jul 29 '12 at 15:46
  • Note that this isn't thread safe. If you're sure that threads aren't started before you enter `main` (and you generally should be), then replacing the definition of the pointer with `Logger* Logger::ourInstance = Logger::instance();` will do the trick. – James Kanze Jul 29 '12 at 15:48
  • @JamesKanze I meant at the end of the program -- lest it causes memory leak. – UltraInstinct Jul 29 '12 at 16:10
  • @JamesKanze: I have to disagree. I normally want to destroy all objects I create. It is the exception when I don't care about leaking it. This goes for singeltons as-well. – Martin York Jul 29 '12 at 20:11
  • @Thrustmaster First, it can't cause a memory leak, because there's only one of them. And second, you don't want to destruct it at the end of the program, because doing so may cause order of destruction issues. – James Kanze Jul 30 '12 at 07:53
  • @LokiAstari I _normally_ want to destroy all objects I create too. From experience, however, wanting to destroy the singleton (and thus expose myself to order of destructor issues) is the exception. Destructing a singleton `Logger`, for example, means that I can't log in destructors. – James Kanze Jul 30 '12 at 07:55
  • @JamesKanze: Experience has taught me there is no issues with order of destruction http://stackoverflow.com/a/335746/14065. Unless you let it happen to yourself. Just force logger to be first constructed and it will be the last destroyed. – Martin York Jul 30 '12 at 08:01
  • @LokiAstari In other words, there are no issues if everything happens according to plan. (If everything happens according to plan, you probably don't need logging.) – James Kanze Jul 30 '12 at 08:24