我正在尝试用 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/