libbmb
Modern implementation of STL
Loading...
Searching...
No Matches
allocator.h
Go to the documentation of this file.
1#pragma once
8#include <cstddef>
9#include <new>
10
11#include "utils/move.h"
12
13namespace bmb {
14
23public:
32 template <typename T>
33 [[nodiscard]]
34 T* allocate(size_t n) {
35 return static_cast<T*>(operator new(n * sizeof(T)));
36 }
37
51 template <typename T>
52 void deallocate(T* ptr, size_t) noexcept {
53 operator delete(ptr);
54 }
55
56 bool operator==(const PrimitiveAllocator&) const { return true; };
57};
58
68template <typename Alloc>
70public:
72
84 template <typename T, typename... Args>
85 static void construct(Alloc& alloc, T* ptr, Args&&... args) {
86 // Use allocator if can
87 if constexpr (requires {
88 alloc.construct(ptr, forward<Args>(args)...);
89 }) {
90 alloc.construct(ptr, forward<Args>(args)...);
91 } else {
92 new (ptr) T(forward<Args>(args)...);
93 }
94 }
95
106 template <typename T>
107 static void destroy(Alloc& alloc, T* ptr) {
108 // Use allocator if can
109 if constexpr (requires { alloc.destroy(ptr); }) {
110 alloc.destroy(ptr);
111 } else ptr->~T();
112 }
113
124 template <typename T>
125 [[nodiscard]]
126 static T* allocate(Alloc& alloc, size_t n) {
127 return alloc.template allocate<T>(n);
128 }
129
139 template <typename T>
140 static void deallocate(Alloc& alloc, T* ptr, size_t n) {
141 alloc.deallocate(ptr, n);
142 }
143};
144
145} // namespace bmb
Unifined interface for allocators.
Definition allocator.h:69
Alloc allocator_type
Definition allocator.h:71
static void deallocate(Alloc &alloc, T *ptr, size_t n)
Deallocates memory under ptr through allocator.
Definition allocator.h:140
static void destroy(Alloc &alloc, T *ptr)
Destroys object throgh alloctor if destroy method is present. Otherwise calls ~T()
Definition allocator.h:107
static void construct(Alloc &alloc, T *ptr, Args &&... args)
Forwards given arguments to allocator's construct method if present. Otherwise uses placement new.
Definition allocator.h:85
static T * allocate(Alloc &alloc, size_t n)
Allocates given number of objects using allocator.
Definition allocator.h:126
Allocator-proxy for new/delete operators.
Definition allocator.h:22
void deallocate(T *ptr, size_t) noexcept
Deallocates memory under ptr.
Definition allocator.h:52
bool operator==(const PrimitiveAllocator &) const
Definition allocator.h:56
T * allocate(size_t n)
Allocates raw memory for n objects of type T.
Definition allocator.h:34
Definition algo_base.h:14
constexpr T && forward(remove_ref_t< T > &value) noexcept
Forward a lvalue.
Definition move.h:33