当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C++ 单例模式

C++ 单例模式

2018年05月03日  | 移动技术网IT编程  | 我要评论

ca4139,mh370找到了,丁水妹

  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;
}    

  要适当的注销代码...

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网