From e327e4469ac2847615f7c847facd5879b5c2e5bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Ankarstr=C3=B6m?= Date: Sun, 28 Aug 2022 04:02:24 +0200 Subject: Replace Managed with Unique. --- c/util.h | 56 ++++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 44 insertions(+), 12 deletions(-) (limited to 'c/util.h') diff --git a/c/util.h b/c/util.h index 0d8a835..ffc6b57 100644 --- a/c/util.h +++ b/c/util.h @@ -28,21 +28,53 @@ struct Finally }; #define FINALLY Finally _ = [=]() -/* Generic RAII type. */ -template -struct Managed +template +inline void Delete(T v) +{ + delete v; +} + +template > +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(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. */ -- cgit v1.2.3