【问题标题】:C++ Singleton class getInstance (as java) [duplicate]C ++ Singleton类getInstance(作为java)[重复]
【发布时间】:2012-07-27 08:43:30
【问题描述】:

可能重复:
Can any one provide me a sample of Singleton in c++?
C++ Singleton design pattern
C++ different singleton implementations

我需要一些 C++ 类中的 Singleton 示例,因为我从未编写过这样的类。 对于 java 中的示例,我可以声明一个私有的静态字段,它在构造函数中初始化,以及一个方法 getInstance,它也是静态的,并返回已经初始化的字段实例。

提前致谢。

【问题讨论】:

标签: c++ singleton


【解决方案1】:
//.h
class MyClass
{
public:
    static MyClass &getInstance();

private:
    MyClass();
};

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

【讨论】:

  • 谢谢,@Roee Gavirel 也给出了相同的答案
  • 不错。我总是使用getInstance==null。静态成员的使用既简单又聪明。
  • 一个潜在的问题是实例将在某个未知的时间点被破坏,可能导致破坏顺序问题。如果单例需要销毁,我使用此解决方案,但如果不需要,则使用指针解决方案(超过 90% 的时间)。
  • @JamesKanze 你能扩展一下破坏顺序的问题吗?
  • @quamrana:未指定破坏静态变量的顺序。因此,例如,如果您有 2 个单例,则未定义哪个将首先被破坏
【解决方案2】:

示例:
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..
}

更多信息在:

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

【讨论】:

  • 链接到外部资源不是一个好主意。如果这些网站消失了,那么您的答案对未来的读者将变得毫无用处。
  • @LokiAstari - 你说得对。我已经修好了。
  • 并且您需要在程序退出之前使用atexit(..) 或手动找到delete 该实例的方法。我个人觉得Andrew's answer更干净。
  • 现在它就在这里。那不是一个好的单身人士。没有所有权的概念。因此无法知道何时删除它,也不会自动销毁。另外,因为您要返回一个指针,所以您正在强制用户检查 null。
  • @Thrustmaster 通常,您不想删除单例。您正在使用它来解决初始化问题的顺序;删除它会引入破坏顺序问题。 (当然,也有例外,您必须将其删除。)
猜你喜欢
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 2011-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多