欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++ 单例模式

程序员文章站 2022-05-24 21:30:33
C++实现单例模式的三种方法 要适当的注销代码... ......

  C++实现单例模式的三种方法

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <mutex>

using namespace std;

class singleton
{
public:
	static singleton *getInstance();
private:
	singleton() = default;
	singleton(const singleton &sle) {}
	static mutex mtx;
	static singleton *instance;
};
singleton *singleton::instance;
mutex singleton::mtx;

// 懒汉式
singleton *singleton::getInstance()
{
	mtx.lock();
	if (instance == NULL)
	{
		instance = new singleton;
	}
	mtx.unlock();
	return instance;
}

// 双重锁式
singleton *singleton::getInstance()
{
    if (instance == NULL)
    {
        mtx.lock();
	if (instance == NULL)
	{
		instance = new singleton();
	}
	mtx.unlock();
    }
    return instance;
}

// 饿汉式
singleton *singleton::instance = new singleton;
singleton *singleton::getInstance()
{
	return instance;
}

void test()
{
	singleton *sle1 = singleton::getInstance();
	singleton *sle2 = singleton::getInstance();

	cout << sle1 << endl;
	cout << sle2 << endl;

	/*singleton sle3 = *sle1;
	cout << &sle3 << endl;*/
}

int main(void)
{
	test();

	system("pause");
	return 0;
}    

  要适当的注销代码...