]> git.tdb.fi Git - libs/core.git/blob - source/core/raii.h
Move non-oneliner functions out of RefPtr class declaration
[libs/core.git] / source / core / raii.h
1 #ifndef MSP_CORE_RAII_H_
2 #define MSP_CORE_RAII_H_
3
4 namespace Msp {
5
6 /**
7 Sets a value for the duration of a scope.  The old value is restored when the
8 scope ends.
9 */
10 template<typename T>
11 class SetForScope
12 {
13 private:
14         T &ref;
15         T old;
16
17 public:
18         SetForScope(T &r, T v): ref(r), old(r) { ref = v; }
19         ~SetForScope() { ref = old; }
20 };
21
22 class SetFlag: public SetForScope<bool>
23 {
24 public:
25         SetFlag(bool &r, bool v = true): SetForScope<bool>(r, v) { }
26 };
27
28
29 template<typename T>
30 class Conditional
31 {
32 private:
33         char buf[sizeof(T)];
34         T *obj;
35
36 public:
37         template<typename A>
38         Conditional(bool c, const A &a): obj(c ? new(buf) T(a) : 0) { }
39
40         template<typename A0, typename A1>
41         Conditional(bool c, const A0 &a0, const A1 &a1): obj(c ? new(buf) T(a0, a1) : 0) { }
42
43         ~Conditional() { if(obj) obj->~T(); }
44 };
45
46 } // namespace Msp
47
48 #endif