vecmem 1.14.0
All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Pages
allocator.ipp
1/*
2 * VecMem project, part of the ACTS project (R&D line)
3 *
4 * (c) 2021 CERN for the benefit of the ACTS project
5 *
6 * Mozilla Public License Version 2.0
7 */
8
9#pragma once
10
11#include <cstddef>
12
13namespace vecmem {
14template <typename T>
16 /*
17 * Since we know the object being allocated here, we can multiply the
18 * number of objects to allocate with the size of that class. We can
19 * also use the compiler's knowledge about the alignment requirements of
20 * the class.
21 */
22 return static_cast<T *>(m_mem.allocate(n * sizeof(T), alignof(T)));
23}
24
25template <typename T>
26void allocator::deallocate_object(T *p, std::size_t n) {
27 /*
28 * Use the upstream allocator to deallocate the memory, again using the
29 * compiler's knowledge about the size and the alignment requirements of
30 * the class that is to be deallocated.
31 */
32 m_mem.deallocate(p, n * sizeof(T), alignof(T));
33}
34
35template <typename T, typename... Args>
37 /*
38 * Firstly we need to allocate some space for the object which we are
39 * constructing. We use the allocate_object method for this, with the
40 * default argument of 1 for a single object.
41 */
42 void *p = allocate_object<T>();
43
44 /*
45 * Next, we use the placement new operation to construct the object in
46 * the memory which we have just allocated. For this, we also need to
47 * forward the arguments passed to this method so they can be used to
48 * call the constructor of the class.
49 */
50 return new (p) T(std::forward<Args>(args)...);
51}
52
53template <typename T>
55 /*
56 * Before ruthlessly destroying the object, we will give it a few last
57 * words to deconstruct itself. This is to ensure it can safely
58 * do any clean-up it needs to do.
59 */
60 p->~T();
61
62 /*
63 * Once the deallocation is complete, we can get rid of the memory as
64 * well. For this, we call the higher-level deallocate_object method.
65 */
67}
68} // namespace vecmem
T * allocate_object(std::size_t n=1)
Allocate space for (a number of) objects.
Definition allocator.ipp:15
T * new_object(Args &&... args)
Allocate and construct a new object.
Definition allocator.ipp:36
void deallocate_object(T *p, std::size_t n=1)
Deallocate space for (a number of) objects.
Definition allocator.ipp:26
void delete_object(T *p)
Deconstruct and deallocate an object.
Definition allocator.ipp:54
Main namespace for the vecmem classes/functions.
Definition atomic_ref.hpp:16
std::vector< T, vecmem::polymorphic_allocator< T > > vector
Alias type for vectors with our polymorphic allocator.
Definition vector.hpp:35