gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:16:59 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com