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

前几天看了 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://stackoverflow.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://stackoverflow.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;
}


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值