gpt4 book ai didi

c++ - 为什么这个单例实现使用私有(private)类(C++)?

转载 作者:太空狗 更新时间:2023-10-29 21:35:50 26 4
gpt4 key购买 nike

因此,我正在处理供应商应用程序中的一些新代码,我观察到他们的一个库使用的是单例模式。他们在那里使用 Helper 来实例化单例。为什么有必要?

库头文件:

Class LibExample {

public:
static LibExample* getInstance();

private:
class Helper {
public:
Helper() {
libExampleInstance = new LibExample();
}
~Helper() {
delete libExampleInstance;
}

LibExample* libExampleInstance;
};

static LibExample* m_instance;

LibExample();
virtual ~LibExample();
LibExample (const LibExample& ) {};
LibExample& operator=(const LibExample&) {
return *(LibExample::getInstance());
}
};

在 .cpp 文件中:

LibExample* LibExample::m_instance = NULL;

LibExample* LibExample::getInstance() {
static Helper instance;
if(m_instance == NULL) {
m_instance = instance.libExampleInstance;
int ret = m_instance->init();
if(ret < 0) {
m_instance = NULL;
}
}
return m_instance;
}

最佳答案

There they use a 'Helper' to instantiate the singleton. Why is that necessary?

事实并非如此。 Helper 可以在这里使用以允许 m_instance == NULL 测试,并在第一次使用 getInstance 时调用 init , 但 init 也可以在 LibExample 构造函数中运行。可能有一个不明确的原因,但恕我直言,这种设计过于复杂。

你可以:

Class LibExample {

public:
static LibExample* getInstance();

private:
LibExample();
virtual ~LibExample();
LibExample (const LibExample& ) {};
LibExample& operator=(const LibExample&) {
return *(LibExample::getInstance());
}
};

LibExample* LibExample::getInstance() {
static LibExample instance;
static LibExample* p_instance = NULL;
if(p_instance == NULL) {
int ret = instance.init();
if(ret >= 0) {
p_instance = &instance;
}
}
return p_instance;
}

编辑:

正如@SingerOfTheFall 在评论中指出的那样:

I think this is done to implement some kind of a late initialization: if init() fails the first time, the singleton itself doesn't need to be re-constructed, and it will try to re-initialize itself the next time the instance is called.

仍然不需要 Helper:我相应地修改了我的代码。

关于c++ - 为什么这个单例实现使用私有(private)类(C++)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41377228/

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