Skip to content

Commit 34c13ef

Browse files
LucasCholletlinusg
authored andcommitted
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.
1 parent 6640cb5 commit 34c13ef

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

AK/OwnPtrWithCustomDeleter.h

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
* Copyright (c) 2022, Lucas Chollet <lucas.chollet@free.fr>
3+
*
4+
* SPDX-License-Identifier: BSD-2-Clause
5+
*/
6+
7+
#pragma once
8+
9+
#include <AK/Function.h>
10+
#include <AK/Noncopyable.h>
11+
#include <AK/StdLibExtras.h>
12+
13+
template<typename T>
14+
struct OwnPtrWithCustomDeleter {
15+
AK_MAKE_NONCOPYABLE(OwnPtrWithCustomDeleter);
16+
17+
public:
18+
OwnPtrWithCustomDeleter(T* ptr, Function<void(T*)> deleter)
19+
: m_ptr(ptr)
20+
, m_deleter(move(deleter))
21+
{
22+
}
23+
24+
OwnPtrWithCustomDeleter(OwnPtrWithCustomDeleter&& other)
25+
{
26+
swap(m_ptr, other.m_ptr);
27+
swap(m_deleter, other.m_deleter);
28+
};
29+
30+
~OwnPtrWithCustomDeleter()
31+
{
32+
if (m_ptr) {
33+
VERIFY(m_deleter);
34+
m_deleter(m_ptr);
35+
}
36+
}
37+
38+
private:
39+
T* m_ptr { nullptr };
40+
Function<void(T*)> m_deleter {};
41+
};

0 commit comments

Comments
 (0)