⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 singleton.h

📁 VIGASOCO (VIdeo GAmes SOurce COde) Windows port (v0.01)
💻 H
字号:
// 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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -