//非线程安全;
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++单例,线程安全,资源释放
最新推荐文章于 2022-11-10 11:27:10 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)