C++ Singleton class getInstance (as java) [duplicate]

拟墨画扇 提交于 2019-12-08 01:28:37

问题


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.


回答1:


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




回答2:


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

private:
    MyClass();
};

//.cpp
MyClass & getInstance()
{ 
    static MyClass instance;
    return instance;
}


来源:https://stackoverflow.com/questions/11708667/c-singleton-class-getinstance-as-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!