OpenVPN 3 Core Library
Loading...
Searching...
No Matches
uniqueptr.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12#ifndef OPENVPN_COMMON_UNIQUEPTR_H
13#define OPENVPN_COMMON_UNIQUEPTR_H
14
15#include <memory>
16#include <functional>
17#include <type_traits>
18
19namespace openvpn {
20template <typename T>
21using unique_ptr_del = std::unique_ptr<T, std::function<void(T *)>>;
22
23// The unique_ptr_slab variation of the std::unique_ptr<T> addresses the issue of
24// new/delete mismatches in code that allocates a _memory slab_ with the global
25// _operator_ new but de-allocates an _object_ with a delete _expression_. The use
26// case that manifests the mismatch is as follows: Allocate a slab of memory that has
27// a C struct at the head of the slab, with a "my_type mt[0];" as the head's last
28// member. The slab is cast to the type of the C struct, but sized to contain N
29// my_type items.
30//
31// The object based de-allocation is the behavior of the std::default_delete<T>
32// template; it is used by the std::unique_ptr<T> if the user does not specify an
33// alternative deleter. The unique_ptr_slab resolves the mismatch with an alternative
34// deleter that de-allocates the _memory slab_ with the global _operator_ delete.
35template <typename T>
36void delete_slab(T *ptr)
37{
38 ::operator delete(const_cast<typename std::remove_cv<T>::type *>(ptr));
39}
40
41template <typename T>
43{
44 public:
46 {
47 }
48 void operator()(T *ptr)
49 {
50 delete_slab(ptr);
51 }
52};
53
54template <typename T>
55using unique_ptr_slab = std::unique_ptr<T, slab_deleter<T>>;
56} // namespace openvpn
57
58#endif
void operator()(T *ptr)
Definition uniqueptr.hpp:48
Support deferred server-side state creation when client connects.
Definition ovpncli.cpp:95
std::unique_ptr< T, std::function< void(T *)> > unique_ptr_del
Definition uniqueptr.hpp:21
void delete_slab(T *ptr)
Definition uniqueptr.hpp:36
std::unique_ptr< T, slab_deleter< T > > unique_ptr_slab
Definition uniqueptr.hpp:55