C++ C++;单例类getInstance(作为java)

C++ C++;单例类getInstance(作为java),c++,singleton,C++,Singleton,可能重复: 在C++类中,我需要一些单子的例子,因为我从来没有写过这样的类。 例如,在java中,我可以声明d是一个静态字段,它是私有的,并且在构造函数中初始化;声明d是一个方法getInstance,它也是静态的,并返回已经初始化的字段实例 提前感谢。示例: //.h class MyClass { public: static MyClass &getInstance(); private: MyClass(); }; //.cpp MyClass &

可能重复:


在C++类中,我需要一些单子的例子,因为我从来没有写过这样的类。 例如,在java中,我可以声明d是一个静态字段,它是私有的,并且在构造函数中初始化;声明d是一个方法getInstance,它也是静态的,并返回已经初始化的字段实例

提前感谢。

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

private:
    MyClass();
};

//.cpp
MyClass & getInstance()
{ 
    static MyClass instance;
    return instance;
}
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;
};
更多信息请访问:


没有。首先,你需要一个很好的理由来使用单例,然后你需要另一个很好的理由,然后我们可以讨论使用单例。请避免使用单例。事实上,它们总是工作的错误工具。先搜索再提问:很抱歉,我没有找到我的问题的任何答案:)请看它是否有效谢谢@Roee Gavirel也给出同样的答案。我总是将
getInstance
==null
一起使用。静态成员的使用既简单又聪明,其中一个潜在的问题是实例将在某个未知的时间点被破坏,可能导致破坏顺序问题。如果单例需要销毁,我使用此解决方案,如果不需要销毁,则使用指针解决方案(这在90%以上的情况下)。@JamesKanze您可以扩展销毁顺序问题吗?@quamrana:未指定销毁静态变量的顺序。因此,如果你有两个单例,例如,它没有定义哪一个将首先被破坏链接到外部资源不是一个好主意。如果这些网站消失了,那么你的答案对未来的读者来说将毫无用处。@LokiAstari-你说得对。我已经解决了。您需要找到一种方法,在程序退出之前,使用
atexit(…)
或手动
删除该实例。我个人觉得更干净。既然它在这里。那不是一个好的单身汉。没有所有权的概念。因此,无法知道何时删除它,也无法自动销毁。另外,由于您返回的是一个指针,因此您强制用户检查null。通常,您不希望删除单例。您正在使用它来解决初始化问题的顺序;删除它将引入销毁顺序问题。(当然,也有例外情况,您必须将其删除。)
#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..
}