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