-
Notifications
You must be signed in to change notification settings - Fork 2
/
scoped.hpp
124 lines (97 loc) · 1.74 KB
/
scoped.hpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#ifndef scoped_H__
#define scoped_H__
namespace testbed
{
////////////////////////////////////////////////////////////////////////////////////////////////////
// scoped_ptr and scoped_linkage_ptr provide end-of-scope actions on arbitrary and external linkage
// pointers, respectively. In addition, scoped_ptr is resettable, while scoped_linkage_ptr comes at
// zero memory overhead.
////////////////////////////////////////////////////////////////////////////////////////////////////
class non_copyable
{
non_copyable(const non_copyable&) {}
non_copyable& operator =(const non_copyable&) { return *this; }
public:
non_copyable() {}
};
template <
typename T,
template< typename F > class FTOR_T,
T* PTR_T >
class scoped_linkage_ptr : non_copyable, FTOR_T< T >
{
public:
~scoped_linkage_ptr()
{
FTOR_T< T >::operator()(PTR_T);
}
};
template <
typename T,
template< typename F > class FTOR_T >
class scoped_ptr : non_copyable, FTOR_T< T >
{
T* m;
public:
scoped_ptr()
: m(0)
{}
explicit scoped_ptr(T* arg)
: m(arg)
{}
~scoped_ptr()
{
if (0 != m)
FTOR_T< T >::operator()(m);
}
void reset()
{
m = 0;
}
void swap(scoped_ptr& oth)
{
T* const t = m;
m = oth.m;
oth.m = t;
}
T* operator ()() const
{
return m;
}
};
template < typename T >
class scoped_functor
{
public:
void operator()(T*);
};
typedef bool (deinit_resources_t)();
template <>
class scoped_functor< deinit_resources_t >
{
public:
void operator()(deinit_resources_t* arg)
{
arg();
}
};
template < typename T >
class generic_delete
{
public:
void operator()(T* arg)
{
delete arg;
}
};
template < typename T >
class generic_delete_arr
{
public:
void operator()(T* arg)
{
delete [] arg;
}
};
} // namespace testbed
#endif // scoped_H__