我在 C++ 语言中找到了这个单例示例:
#include <iostream>
class singleton {
private:
// ecco il costruttore privato in modo che l'utente non possa istanziare direttamante
singleton() { };
public:
static singleton& get_instance()
{
// l'unica istanza della classe viene creata alla prima chiamata di get_instance()
// e verrà distrutta solo all'uscita dal programma
static singleton instance;
return instance;
}
bool method() { return true; };
};
int main() {
std::cout << singleton::get_instance().method() << std::endl;
return 0;
}
但是,这怎么可能是单例类呢?
只创建一个实例的控件在哪里?
不要错过静态属性?
如果我在主函数中编写另一个 get_instance() 调用会怎样?
最佳答案
单实例控制是使用 get_instance
中的函数范围静态完成的。此类对象在程序流首先通过它们时构造一次,并在程序退出时销毁。因此,您第一次调用 get_instance
时,将构造并返回单例。每隔一段时间将返回相同的对象。
这通常称为 Meyers singleton .
关于c++ - 单例示例如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34787288/