diff options
Diffstat (limited to 'c/util.h')
-rw-r--r-- | c/util.h | 56 |
1 files changed, 44 insertions, 12 deletions
@@ -28,21 +28,53 @@ struct Finally }; #define FINALLY Finally _ = [=]() -/* Generic RAII type. */ -template <typename T, auto F, typename U, auto E = 0> -struct Managed +template <typename T> +inline void Delete(T v) +{ + delete v; +} + +template <typename T, auto F = Delete<T>> +struct Unique { - T obj; - Managed(T obj) : obj(obj) + T v; + bool ok = true; + Unique() : ok(false) {} + Unique(T v) : v(v) {} + Unique& operator =(T v_) + { + if (ok) + F(v); + v = v_; + ok = true; + return *this; + } + Unique(Unique&& other) + { + v = std::move(other.v); + other.ok = false; + } + Unique& operator =(Unique&& other) + { + if (ok) + F(v); + v = std::move(other.v); + ok = other.ok; + other.ok = false; + return *this; + } + bool Not(T u) + { + if (v == u) + return ok = false; + else + return true; + } + ~Unique() { - if (obj == reinterpret_cast<T>(E)) - throw U(); + if (ok) + F(v); } - ~Managed() { F(obj); } - operator T() { return obj; } - auto& operator *() { return *obj; } - auto& operator ->() { return obj; } - auto& operator [](size_t i) { return obj[i]; } }; /* Buf is a span-like structure of a buffer and its size. */ |