Zen C++ Libraries
Zero-dependency re-usable components for C++
Loading...
Searching...
No Matches
alloc.hpp
Go to the documentation of this file.
1
9
10#ifndef ZEN_ALLOC_HPP
11#define ZEN_ALLOC_HPP
12
13#include <concepts>
14#include <new>
15#include <utility>
16
17#include "zen/config.hpp"
18
19ZEN_NAMESPACE_START
20
53using destroy_fn = void (*)(void *);
54
61template<typename T>
62concept DynamicAllocator = requires (
63 T& t,
64 std::size_t size,
65 std::size_t alignment,
66 destroy_fn destroy
67) {
68 { t.allocate(size, alignment, destroy) } -> std::same_as<void*>;
69};
70
77template<typename R, DynamicAllocator Alloc, typename ...Ts>
78R* construct(Alloc& allocator, Ts&& ...args) {
79 auto ptr = allocator.allocate(
80 sizeof(R),
81 alignof(R),
82 [](void* ptr) { static_cast<R*>(ptr)->~R(); }
83 );
84 if (ZEN_UNLIKELY(!ptr)) {
85 return nullptr;
86 }
87 ::new (ptr) R (std::forward<Ts>(args)...);
88 return std::launder(reinterpret_cast<R*>(ptr));
89}
90
91ZEN_NAMESPACE_END
92
93#endif // of #ifndef ZEN_ALLOC_HPP
R * construct(Alloc &allocator, Ts &&...args)
Definition alloc.hpp:78
void(*)(void *) destroy_fn
Definition alloc.hpp:53
Definition alloc.hpp:62