c++单例类实例访问整个应用程序

标签 c++

我正在尝试用 C++ 中的线程安全实践编写一个日志类。现在的问题是,我想让对每个日志行的调用变得非常简单。我可以使用如下静态类方式:

//Calling this in some GUI initialization point of application
CLogger::InitLogger("LogFile.log");

//Calling below from any class just adding the header to the cpp
CLogger::Log("Some informational text goes here");

现在这不遵循 OOP,所以想使用单例类。

//Singleton log class
class CLogWrite
{
public:
  static CLogWrite* GetInstance();

private:
  static CLogWrite *pInstance;
  void Log();
};

CLogWrite* CLogWrite::GetInstance()
{
  if(pInstance != NULL)
  {
    pInstance = new CLogWrite;
  }
  return pInstance;
}

void CLogWrite::Log()
{
  //threadSafe lock

  //write 'logText' to file here

  //threadSafe unlock
}

现在的问题是,如果我编写上面的类并在我的 GUI 类初始化函数中调用 CLogWriter::GetInstance(),如下所示:

//single logger instance for my app
CLogWriter *mLogInstance;
mLogInstance = CLogWriter::GetInstance()

我需要将“mLogInstance”变量传递给项目中我想写日志的每个类。但我不想那样做。

什么是最好的方法?

最佳答案

试试这个:

class Singleton
{
public:
    static Singleton& getInstance()
    {
        static Singleton instance;
        return instance;
    }

    Singleton(Singleton const&) = delete;
    void operator=(Singleton const&) = delete;

private:
    Singleton() {};        
};

关于c++单例类实例访问整个应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29577447/

相关文章:

c++ - 从 'QTableWidgetItem* const' 到 'QChar' 的转换......或者 QString......是不明确的

c++ - 如何从 TOKEN_INFORMATION_CLASS 获取 PSID?

c++ - 使用元素加载 std::queue<uint8_t*> 的更有效方法?

c++ - 保证检测临时->命名点

c++ - 如何在C应用程序中使用C++ DLL?

c++ - 在 c++ w/directx 中测试正方形是否与多边形重叠(可选)

c++ - 另一种复制算法

c++ - 为什么 std::fstream 返回 void 而不是 bool

c++ - qdir.h 与 x.h (X11) : how to resolve? 冲突

c++ - 将组合框信号连接到 Qt 中的 std::function 的问题