📄 singleton.h
字号:
/* -*- C++ -*- */
#ifndef _XP_SINGLETON_H
#define _XP_SINGLETON_H
/**
* @class Singleton
*
* If you want to make sure that only the singleton instance of
* <T> is created, and that users cannot create their own
* instances of <T>, do the following to class <T>:
* (a) Make the constructor of <T> private (or protected)
* (b) Make Singleton a friend of <T>
* Here is an example:
* class foo
* {
* friend class Singleton<foo>;
* private:
* foo () { cout << "foo constructed" << endl; }
* ~foo () { cout << "foo destroyed" << endl; }
* };
* typedef Singleton<foo> FOO;
*
*/
template <typename TYPE,typename _A = std::allocator<TYPE> >
class Singleton
{
public:
/// Global access point to the Singleton.
static TYPE *instance (void)
{
Singleton<TYPE> &singleton = Singleton<TYPE>::instance_i ();
if (singleton.instance_ == 0)
{
_A a;
singleton.instance_ = a.allocate(1, NULL);
a.construct(singleton.instance_, TYPE());
}
return singleton.instance_;
}
/// Explicitly delete the Singleton instance.
static void close (void)
{
Singleton<TYPE> &singleton = Singleton<TYPE>::instance_i ();
if (singleton.instance_)
{
_A a;
a.destroy(singleton.instance_ );
a.deallocate(singleton.instance_ , 1);
}
}
protected:
/// Contained instance.
TYPE *instance_;
/// Get pointer to the Singleton instance.
static Singleton<TYPE> &instance_i (void)
{
static Singleton<TYPE> singleton_;
return singleton_;
}
};
#endif /* _XP_SINGLETON_H */
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -