mirror of
https://github.com/SerenityOS/serenity.git
synced 2025-01-23 09:51:57 -05:00
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.
This commit is contained in:
parent
6640cb57b3
commit
34c13eff11
1 changed files with 41 additions and 0 deletions
41
AK/OwnPtrWithCustomDeleter.h
Normal file
41
AK/OwnPtrWithCustomDeleter.h
Normal file
|
@ -0,0 +1,41 @@
|
|||
/*
|
||||
* Copyright (c) 2022, Lucas Chollet <lucas.chollet@free.fr>
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AK/Function.h>
|
||||
#include <AK/Noncopyable.h>
|
||||
#include <AK/StdLibExtras.h>
|
||||
|
||||
template<typename T>
|
||||
struct OwnPtrWithCustomDeleter {
|
||||
AK_MAKE_NONCOPYABLE(OwnPtrWithCustomDeleter);
|
||||
|
||||
public:
|
||||
OwnPtrWithCustomDeleter(T* ptr, Function<void(T*)> 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<void(T*)> m_deleter {};
|
||||
};
|
Loading…
Add table
Reference in a new issue