From 34c13eff118dac177400a03021f4860eeb9a36ef Mon Sep 17 00:00:00 2001 From: Lucas CHOLLET Date: Fri, 9 Dec 2022 16:24:16 +0100 Subject: [PATCH] AK: Add `OwnPtrWithCustomDeleter` This class is a smart pointer that let you provide a custom deleter to free the pointer. It is quite primitive compared to other smart pointers but can still be useful when interacting with C types that provides a custom `free()` function. --- AK/OwnPtrWithCustomDeleter.h | 41 ++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 AK/OwnPtrWithCustomDeleter.h diff --git a/AK/OwnPtrWithCustomDeleter.h b/AK/OwnPtrWithCustomDeleter.h new file mode 100644 index 00000000000..f9968810ed3 --- /dev/null +++ b/AK/OwnPtrWithCustomDeleter.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022, Lucas Chollet + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include +#include +#include + +template +struct OwnPtrWithCustomDeleter { + AK_MAKE_NONCOPYABLE(OwnPtrWithCustomDeleter); + +public: + OwnPtrWithCustomDeleter(T* ptr, Function deleter) + : m_ptr(ptr) + , m_deleter(move(deleter)) + { + } + + OwnPtrWithCustomDeleter(OwnPtrWithCustomDeleter&& other) + { + swap(m_ptr, other.m_ptr); + swap(m_deleter, other.m_deleter); + }; + + ~OwnPtrWithCustomDeleter() + { + if (m_ptr) { + VERIFY(m_deleter); + m_deleter(m_ptr); + } + } + +private: + T* m_ptr { nullptr }; + Function m_deleter {}; +};