C++单例模式的一种实现
//singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
#include <iostream>
#include <mutex>
using namespace std;
class singleton //单例的一种实现
{
private:
static mutex mutex_obj;
static int i;
static singleton *singleton_p;
singleton();
public:
static singleton * Instance();
static void print();
};
#endif // SINGLETON_H
//singleton.cpp
#include "singleton.h"
singleton* singleton::singleton_p=nullptr;
int singleton::i = 10;
mutex singleton::mutex_obj;
singleton::singleton(){
i++;
cout << "i:" << i << endl;
}
singleton * singleton::Instance(){
if(singleton_p == nullptr){
//doing...
mutex_obj.lock();
if(singleton_p == nullptr){
singleton_p = new singleton();
}
mutex_obj.unlock();
}
return singleton_p;
}
void singleton::print(){
cout << "i:" << i << endl;
}
//main.cpp
#include <iostream>
#include "singleton.h"
using namespace std;
int main(int argc, char *argv[])
{
singleton *p = singleton::Instance();
cout << p << endl;
p->print();
p = singleton::Instance();
cout << p << endl;
p->print();
return 0;
}
记C++单例模式的一种实现方式:
它在线程中是安全的;
实例在首次调用Instance函数时创建;
实例存在于堆中;
进程结束时释放;