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;

	/*Person p3 = *p1;
	cout << &p3 << endl;*/
}

int main(void)
{
	test();

	system("pause");
	return 0;
}    

  要适当的注销代码...

猜你喜欢

转载自www.cnblogs.com/xueyeduling/p/8983349.html