aboutsummaryrefslogtreecommitdiff
path: root/include/cru/base/Guard.h
diff options
context:
space:
mode:
authorYuqian Yang <crupest@crupest.life>2025-11-18 20:25:52 +0800
committerYuqian Yang <crupest@crupest.life>2025-11-18 20:25:52 +0800
commiteca67e7d2bd227433eb4b47b499cfcc0106a3eaa (patch)
treeb037f6f2f39ef40b0cfa983ec42efefc87c5d70f /include/cru/base/Guard.h
parent0263f0a3fa0760afae94909700f8f6c52ec7c750 (diff)
downloadcru-eca67e7d2bd227433eb4b47b499cfcc0106a3eaa.tar.gz
cru-eca67e7d2bd227433eb4b47b499cfcc0106a3eaa.tar.bz2
cru-eca67e7d2bd227433eb4b47b499cfcc0106a3eaa.zip
Fix AutoFreePtr.
Diffstat (limited to 'include/cru/base/Guard.h')
-rw-r--r--include/cru/base/Guard.h44
1 files changed, 10 insertions, 34 deletions
diff --git a/include/cru/base/Guard.h b/include/cru/base/Guard.h
index 65e2dee4..c05bc668 100644
--- a/include/cru/base/Guard.h
+++ b/include/cru/base/Guard.h
@@ -29,51 +29,27 @@ struct Guard {
ExitFunc on_exit;
};
-/**
- * FreeFunc must handle nullptr correctly.
- */
-template <typename T, void (*FreeFunc)(T*) noexcept>
-struct TAutoFreePtr {
- TAutoFreePtr(T* ptr) : ptr(ptr) {}
- ~TAutoFreePtr() { FreeFunc(ptr); }
-
- CRU_DELETE_COPY(TAutoFreePtr)
-
- TAutoFreePtr(TAutoFreePtr&& other) noexcept : ptr(other.ptr) {
- other.ptr = nullptr;
- }
-
- TAutoFreePtr& operator=(TAutoFreePtr&& other) noexcept {
- if (this != &other) {
- FreeFunc(ptr);
- ptr = other.ptr;
- other.ptr = nullptr;
- }
- return *this;
- }
-
- operator T*() const { return ptr; }
- T* operator->() { return ptr; }
-
- T* ptr;
-};
-
namespace details {
template <typename T>
-inline void MyFree(T* p) noexcept {
- ::free(p);
-}
+struct AutoFreePtrDeleter {
+ void operator()(T* ptr) const noexcept { ::free(ptr); }
+};
} // namespace details
template <typename T>
-using AutoFreePtr = TAutoFreePtr<T, details::MyFree<T>>;
+using AutoFreePtr = std::unique_ptr<T, details::AutoFreePtrDeleter<T>>;
+
+template <typename T>
+inline AutoFreePtr<T> MakeAutoFree(T* ptr) {
+ return AutoFreePtr<T>(ptr);
+}
template <typename T, void (*DestructFunc)(T value) noexcept>
class AutoDestruct {
public:
AutoDestruct() : value_(std::nullopt), auto_destruct_(false) {}
- AutoDestruct(T value, bool auto_destruct = true)
+ explicit AutoDestruct(T value, bool auto_destruct = true)
: value_(std::move(value)), auto_destruct_(auto_destruct) {}
CRU_DELETE_COPY(AutoDestruct)