blob: de43dbe4dac686deaee84eff1a163845fcf608ea (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
#ifndef __SINGLETON_H
#define __SINGLETON_H
#include "ScopedPtr.hpp"
#include "NonCopyable.hpp"
#include "UtilExportable.hpp"
#include "Noreturn.hpp"
#include <cstdlib>
#include <stdexcept>
#define DECLARE_SINGLETON( T ) \
friend class Singleton< T >; \
friend class scopedPtr< T >;
#define DEFINE_SINGLETON( T ) \
template class Singleton< T >;
template< class T >
class Singleton : private noncopyable
{
public:
static UTIL_DLL_VISIBLE T& instance( )
{
if( destroyed ) {
onDeadReference( );
}
if( t == 0 ) {
create( );
}
return *t;
}
protected:
Singleton( )
{
}
virtual ~Singleton( )
{
destroyed = true;
}
private:
static void create( )
{
t.reset( new T );
}
static void onDeadReference( ) CRAWLER_NORETURN
{
throw std::runtime_error( "singleton has already been destroyed!" );
}
static scopedPtr<T> t;
static bool destroyed;
};
template< class T > scopedPtr<T> Singleton<T>::t( 0 );
template< class T > bool Singleton<T>::destroyed( false );
#endif
|