sandbox
Loading...
Searching...
No Matches
aligned_storage.hpp
1#ifndef LIBSBX_MEMORY_ALIGNED_STORAGE_HPP_
2#define LIBSBX_MEMORY_ALIGNED_STORAGE_HPP_
3
4#include <memory>
5#include <type_traits>
6#include <cinttypes>
7
8namespace sbx::memory {
9
10template<std::size_t Size, std::size_t Alignment>
12 struct type {
13 alignas(Alignment) std::byte data[Size];
14 }; // union type
15}; // struct aligned_storage
16
17template<std::size_t Size, std::size_t Alignment>
18using aligned_storage_t = typename aligned_storage<Size, Alignment>::type;
19
20template<typename Type>
22 // using type = alignas(alignof(Type)) std::byte[sizeof(Type)];
23 struct alignas(alignof(Type)) type {
24 std::byte data[sizeof(Type)];
25 }; // struct type
26}; // struct storage_for
27
28template<typename Type>
29using storage_for_t = typename storage_for<Type>::type;
30
39template<typename Type>
41
42public:
43
44 using value_type = Type;
45
46 constructible() = default;
47
48 constructible(const constructible& other) = delete;
49 constructible(constructible&& other) = delete;
50
51 ~constructible() = default;
52
53 auto operator=(const constructible& other) -> constructible& = delete;
54 auto operator=(constructible&& other) -> constructible& = delete;
55
56 template<typename... Args>
57 requires (std::is_constructible_v<Type, Args...>)
58 auto construct(Args&&... args) -> Type* {
59 return std::construct_at(_ptr(), std::forward<Args>(args)...);
60 }
61
62 auto destroy() noexcept -> void {
63 std::destroy_at(_ptr());
64 }
65
66 auto get() noexcept -> Type* {
67 return _ptr();
68 }
69
70 auto get() const noexcept -> const Type* {
71 return _ptr();
72 }
73
74 auto operator*() noexcept -> Type& {
75 return *_ptr();
76 }
77
78 auto operator*() const noexcept -> const Type& {
79 return *_ptr();
80 }
81
82private:
83
84 auto _ptr() noexcept -> Type* {
85 return std::launder(reinterpret_cast<Type*>(&_storage));
86 }
87
88 auto _ptr() const noexcept -> const Type* {
89 return std::launder(reinterpret_cast<const Type*>(&_storage));
90 }
91
92 storage_for_t<Type> _storage;
93
94}; // class optional
95
96} // namespace sbx::memory
97
98#endif // LIBSBX_MEMORY_ALIGNED_STORAGE_HPP_
A class that allows for the manual construction and destruction of an object of type Type.
Definition: aligned_storage.hpp:40
Definition: aligned_storage.hpp:12
Definition: aligned_storage.hpp:11
Definition: aligned_storage.hpp:23
Definition: aligned_storage.hpp:21