xref: /freebsd/lib/libutil++/freebsd__malloc_up.3 (revision 086ce467adec42d58414fdb4d54c2b6819cf0c07)
1.\"
2.\" SPDX-License-Identifier: BSD-2-Clause
3.\"
4.\" Copyright (c) 2025 Chelsio Communications, Inc.
5.\" Written by: John Baldwin <jhb@FreeBSD.org>
6.\"
7.Dd July 31, 2025
8.Dt FREEBSD::MALLOC_UP 3
9.Os
10.Sh NAME
11.Nm freebsd::malloc_up
12.Nd std::unique_ptr specialization for objects allocated via malloc
13.Sh LIBRARY
14.Lb libutil++
15.Sh SYNOPSIS
16.In libutil++.hh
17.Ft using malloc_up = std::unique_ptr<T, free_deleter<T>>;
18.Sh DESCRIPTION
19This class is a specialization of
20.Vt std::unique_ptr
21which invokes
22.Xr free 3
23instead of
24.Fn delete
25when an object is disposed.
26While explicit calls to
27.Xr malloc 3
28should be avoided in C++ code,
29this class can be useful to manage an object allocated by an existing API
30which uses
31.Xr malloc 3
32internally such as
33.Xr scandir 3 .
34Note that the type of the underlying object must be used as the first
35template argument similar to std::unique_ptr.
36.Sh EXAMPLES
37This example uses
38.Xr strdup 3
39for simplicity,
40but new C++ code should generally not use
41.Xr strdup 3 :
42.Bd -literal -offset indent
43freebsd::malloc_up<char> my_string(strdup("foo"));
44// `mystring' is implicitly freed on destruction
45.Ed
46.Sh SEE ALSO
47.Xr free 3 ,
48.Xr malloc 3 ,
49.Xr scandir 3 ,
50.Xr strdup 3
51