-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIStaticInstance.h
46 lines (40 loc) · 1.06 KB
/
IStaticInstance.h
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
#ifndef _ISTATICINSTANCE_H
#define _ISTATICINSTANCE_H
// A variation of a singleton, whereas a single static instance
// is selectable and assignable to be primary for a given class.
// Lifetime is controllable through a shared_ptr
#include <memory>
#include "Util.h"
template<class T>
class IStaticInstance
{
public:
enum Flags {
FREE = BIT(0)
};
static std::shared_ptr<T> shared(T* p = NULL, unsigned int flags = 0){
static std::shared_ptr<T> instance;
if(!(flags & FREE))
{
if(p)
instance.reset(p);
}
else
instance.reset();
return instance;
}
static std::weak_ptr<T> weak(){
std::weak_ptr<T> w(shared());
return w;
}
static T& get(T* p = NULL){
return *shared(p);
}
static T* ptr(T* p = NULL){
return &*shared(p);
}
static void reset() {
shared(NULL, FREE);
}
};
#endif