我正在尝试使用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类init函数中调用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() {};
};

10-01 00:14