//非线程安全;
class Singleton {
public:
static Singleton& GetInstance() {
static Singleton instance;//对象构造过程中可能线程切换到另一个线程;
return instance;
}
void test() { cout << "test!!!" << endl; }
private:
Singleton() {}
Singleton(const Singleton& );
Singleton& operator=(const Singleton& );
};
//懒汉模式:非线程安全,第一次调用才进行初始化;
class SingletonLazy {
public:
static SingletonLazy* GetInstance() {
if (spts == nullptr)
// 有可能在此时出现线程切换,而此时spts为空;
spts = new SingletonLazy();
return spts;
}
void test() { cout << "class lazy!!!" << endl; }
private:
static SingletonLazy* spts;
SingletonLazy(){}
SingletonLazy(const SingletonLazy&);
SingletonLazy& operator=(const SingletonLazy&);
};
SingletonLazy* SingletonLazy::spts = nullptr;
//线程安全的懒汉模式:使用双检锁DCL机制
class SingletonLazySafe {
public:
static SingletonLaz
C++单例,线程安全,资源释放
最新推荐文章于 2024-02-20 22:43:01 发布
本文详细介绍了如何在C++中实现一个线程安全的单例模式,确保在多线程环境下正确且唯一地创建实例。同时,探讨了单例模式在资源管理上的应用,包括如何在程序退出时优雅地释放资源,以避免内存泄漏问题。通过实例代码和分析,读者将深入理解C++单例模式的设计和实现技巧。
摘要由CSDN通过智能技术生成