|
发表于 2004-9-8 13:33:00
|
显示全部楼层
Re:Lib中的static变量怎么会对外不可见
干脆来贴全了,新的singleton基本上都是这么实现的。
template<class T>
class singleton: private T
{
private:
singleton();
~singleton();
public:
static T &instance();
};
template<class T>
inline singleton<T>::singleton()
{ /* no-op */ }
template<class T>
inline singleton<T>::~singleton()
{ /* no-op */ }
template<class T>
/*static*/ T &singleton<T>::instance()
{
// function-local static to force this to work correctly at static
// initialization time.
static singleton<T> s_oT;
return(s_oT);
}
// T must be: no-throw default constructible and no-throw destructible
template <typename T>
struct singleton_default
{
private:
struct object_creator
{
// This constructor does nothing more than ensure that instance()
// is called before main() begins, thus creating the static
// T object before multithreading race issues can come up.
object_creator() { singleton_default<T>::instance(); }
inline void do_nothing() const { }
};
static object_creator create_object;
singleton_default();
public:
typedef T object_type;
// If, at any point (in user code), singleton_default<T>::instance()
// is called, then the following function is instantiated.
static object_type & instance()
{
// This is the object that we return a reference to.
// It is guaranteed to be created before main() begins because of
// the next line.
static object_type obj;
// The following line does nothing else than force the instantiation
// of singleton_default<T>::create_object, whose constructor is
// called before main() begins.
create_object.do_nothing();
return obj;
}
};
template <typename T>
typename singleton_default<T>: bject_creator
singleton_default<T>::create_object; |
|