C ++ Singleton class getInstance (like java)

Possible duplicate:
Can someone provide me a Singleton sample in C ++?
C ++ Singleton design pattern
C ++ various single versions

I need a Singleton example in a C ++ class because I have never written such a class. For example, in java, I can declare d a static field that is private, and it is initialized in the constructor and the getInstance method, which is also static and returns an instance of the initialization field.

Thanks in advance.

+2
c ++ singleton
source share
2 answers

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.. } 

Additional Information:

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

+2
source share
 //.h class MyClass { public: static MyClass &getInstance(); private: MyClass(); }; //.cpp MyClass & getInstance() { static MyClass instance; return instance; } 
+4
source share

All Articles