mirror of
https://github.com/Light-City/CPlusPlusThings.git
synced 2026-02-04 11:03:58 +08:00
update
This commit is contained in:
42
design_pattern/singleton/dcl_singleton.cpp
Normal file
42
design_pattern/singleton/dcl_singleton.cpp
Normal file
@@ -0,0 +1,42 @@
|
||||
//
|
||||
// Created by light on 20-2-7.
|
||||
//
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
#include <mutex>
|
||||
|
||||
class singleton {
|
||||
private:
|
||||
singleton() {}
|
||||
|
||||
static singleton *p;
|
||||
static mutex lock_;
|
||||
public:
|
||||
singleton *instance();
|
||||
|
||||
// 实现一个内嵌垃圾回收类
|
||||
class CGarbo
|
||||
{
|
||||
public:
|
||||
~CGarbo()
|
||||
{
|
||||
if(singleton::p)
|
||||
delete singleton::p;
|
||||
}
|
||||
};
|
||||
static CGarbo Garbo; // 定义一个静态成员变量,程序结束时,系统会自动调用它的析构函数从而释放单例对象
|
||||
};
|
||||
|
||||
singleton *singleton::p = nullptr;
|
||||
singleton::CGarbo Garbo;
|
||||
|
||||
singleton* singleton::instance() {
|
||||
if (p == nullptr) {
|
||||
lock_guard<mutex> guard(lock_);
|
||||
if (p == nullptr)
|
||||
p = new singleton();
|
||||
}
|
||||
return p;
|
||||
}
|
||||
Reference in New Issue
Block a user