C++中实现singleton(单例模式)的最简单写法

时间:2022-08-11 20:50:45

前几天看了 Java中实现singleton的写法,就想在C++中实现一下,找了很多资料,看了各个牛人写的不同版本,但最后在stack overflow上找到了一个最简单的写法,不需要判断是否已经有实例存在,则在多线程的情况也可以正常使用,现在贴出来以供参考:

class S
{
public:
static S& getInstance()
{
static S instance;
return instance;
}
private:
S() {}; // Constructor
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
};
它其实是使用了C++中成员函数的静态变量的特点:静态局部变量在第一次使用时初始化,并不会销毁直到程序退出。

具体资料:http://*.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function

下面是我总结的四种singleton在C++中的实现方法:


// Singleton.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <Windows.h>
using namespace std;

//C++ Singleton Version 1
class Singleton1
{
private:
Singleton1(){};
static Singleton1* instance;
virtual ~Singleton1(void){}
public:
int ia;
static Singleton1* GetInstance()
{
if (NULL == instance)
{
instance = new Singleton1();
}
return instance;
}
};
//Must define static member, not just declaration
Singleton1* Singleton1::instance = NULL;

//C++ Singleton Version 2
//Use smart point to release memory
#include <memory>
using namespace std;
class Singleton2
{
public:
static Singleton2 * GetInstance()
{
if (NULL == instance.get())
{
instance.reset(new Singleton2());
}
return instance.get();
}
int ia;
private:
static shared_ptr<Singleton2> instance;

};
shared_ptr<Singleton2> Singleton2::instance;

//C++ Singleton Version 3
//Use template to reduce some duplicate work
template <class T>
class Singleton
{
public:
static T* GetInstance();
private:
Singleton(){}
~Singleton(){}
Singleton(const Singleton&){}
Singleton& operator=(const Singleton&){}

static shared_ptr<T> instance;
};

template <class T>
shared_ptr<T> Singleton<T>::instance;

template <class T>
T* Singleton<T>::GetInstance()
{
if (NULL = instance.get())
{
instance.reset(new Singleton());
}
return instance.get();
}

//C++ Singleton Version 4
//Avoid memory allocation
class Singleton4
{
public:
static Singleton4& GetInstance()
{
// Guaranteed to be destroyed.
// Instantiated on first use.
// Static variable lifetime in function-http://*.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function
static Singleton4 instance;
return instance;
}
private:
Singleton4(){}
~Singleton4(){}
// Dont forget to declare these two. You want to make sure they
// are unaccessable otherwise you may accidently get copies of
// your singleton appearing.
Singleton4(Singleton4 const&);//Don't Implement
void operator=(Singleton4 const&);//Don't Implement
};


int _tmain(int argc, _TCHAR* argv[])
{
/* version 1: Memory leak
Singleton1* a = Singleton1::GetInstance();
a->ia = 100;
Singleton1* b = Singleton1::GetInstance();
cout << b->ia << endl;
*/

Singleton2* a2 = Singleton2::GetInstance();
a2->ia = 200;
Singleton2* b2 = Singleton2::GetInstance();
cout << b2->ia << endl;
OutputDebugString(_T("hello world!"));

system("pause");

return 0;
}