#include <iostream>
class Singleton {
private:
static Singleton* instance; // 指向单例实例的指针
Singleton() {} // 私有构造函数
public:
// 获取单例对象的唯一全局访问点
static Singleton* getInstance() {
if (instance == nullptr) { // 懒加载
instance = new Singleton();
}
return instance;
}
// 示例成员函数
void doSomething() {
std::cout << "Doing something..." << std::endl;
}
};
Singleton* Singleton::instance = nullptr; // 静态初始化单例实例
int main() {
Singleton* s1 = Singleton::getInstance();
Singleton* s2 = Singleton::getInstance();
// 验证s1和s2是否指向同一个对象
if (s1 == s2) {
std::cout << "s1 and s2 are the same instance." << std::endl;
}
s1->doSomething();
s2->doSomething();
return 0;
}