C++ singleton pattern

  Three ways to implement the singleton pattern in 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;

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

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

// Hungry Chinese
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;
}    

  To have a proper logout code...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325170815&siteId=291194637