singleton.h

来自「VIGASOCO (VIdeo GAmes SOurce COde) Windo」· C头文件 代码 · 共 56 行

H
56 行
字号
// Singleton.h
//
//	Automatic singleton utility class (Singleton pattern)
//	(Presented by Scott Bilas in Game Programming Gems)
//
//	How to use it: class MySingleton: public Singleton<MySingleton>
//
/////////////////////////////////////////////////////////////////////////////

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

#ifdef _MSC_VER
#pragma warning (disable : 4311)
#pragma warning (disable : 4312)
#endif

#include <cassert>


template <typename T>
class Singleton
{
	static T *g_singleton;	// the singleton object

// methods
public:
	// constructor
	Singleton()
	{
		assert(!g_singleton);

		// trick to get the correct pointer in case of multiple inheritance
		// cast an unexistant object at address 1 to both types and get the offset
		int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1;
		g_singleton = (T*)((int)this + offset);
	}

	// destructor
	~Singleton()
	{
		assert(g_singleton != 0);

		g_singleton = 0;
	}

	// getters
	static T& getSingleton() { assert(g_singleton); return *g_singleton; }
	static T *getSingletonPtr() { return g_singleton; }
};


template <typename T> T* Singleton<T>::g_singleton = 0;


#endif	// _SINGLETON_H_

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?