diff options
author | Steven Le Rouzic <steven.lerouzic@gmail.com> | 2024-11-19 23:30:55 +0100 |
---|---|---|
committer | Steven Le Rouzic <steven.lerouzic@gmail.com> | 2024-12-20 15:35:58 +0100 |
commit | f5ef1937eafb3d96b3683d92639a193694210c70 (patch) | |
tree | 0edcffc7447c42fe8467e2b788ee8f65f96b7fe2 /asl/box.hpp | |
parent | 3bddc19f5854857788330f11993336f645c414ab (diff) |
More work on asl::box
Diffstat (limited to 'asl/box.hpp')
-rw-r--r-- | asl/box.hpp | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/asl/box.hpp b/asl/box.hpp index 0cab66b..d8ccd36 100644 --- a/asl/box.hpp +++ b/asl/box.hpp @@ -1,7 +1,10 @@ #pragma once
#include "asl/allocator.hpp"
+#include "asl/assert.hpp"
#include "asl/annotations.hpp"
+#include "asl/memory.hpp"
+#include "asl/utility.hpp"
namespace asl
{
@@ -13,7 +16,87 @@ class box ASL_NO_UNIQUE_ADDRESS Allocator m_alloc;
public:
+ explicit constexpr box(T* ptr = nullptr)
+ requires default_constructible<Allocator>
+ : m_ptr{ptr}
+ {}
+
+ constexpr box(T* ptr, Allocator alloc)
+ : m_ptr{ptr}
+ , m_alloc{ASL_MOVE(alloc)}
+ {}
+
+ constexpr box(box&& other)
+ : m_ptr{exchange(other.m_ptr, nullptr)}
+ , m_alloc{ASL_MOVE(other.m_alloc)}
+ {}
+
+ constexpr box& operator=(box&& other)
+ {
+ if (this == &other) { return *this; }
+
+ if (m_ptr != nullptr) { reset(); }
+
+ m_ptr = exchange(other.m_ptr, nullptr);
+ m_alloc = ASL_MOVE(other.m_alloc);
+
+ return *this;
+ }
+
+ box(const box&) = delete;
+ box& operator=(const box&) = delete;
+
+ constexpr ~box()
+ {
+ reset();
+ }
+
+ constexpr void reset()
+ {
+ if (m_ptr != nullptr)
+ {
+ if constexpr (!trivially_destructible<T>)
+ {
+ m_ptr->~T();
+ }
+ m_alloc.dealloc(m_ptr, layout::of<T>());
+ m_ptr = nullptr;
+ }
+ }
+
+ constexpr T* get() const { return m_ptr; }
+
+ constexpr T& operator*() const
+ {
+ ASL_ASSERT(m_ptr != nullptr);
+ return *m_ptr;
+ }
+
+ constexpr T* operator->() const
+ {
+ ASL_ASSERT(m_ptr != nullptr);
+ return m_ptr;
+ }
};
+template<is_object T, allocator Allocator = DefaultAllocator, typename... Args>
+constexpr box<T, Allocator> make_box_in(Allocator allocator, Args&&... args)
+ requires constructible_from<T, Args&&...>
+{
+ void* raw_ptr = allocator.alloc(layout::of<T>());
+ T* ptr = new (raw_ptr) T(ASL_FWD(args)...);
+ return box(ptr, ASL_MOVE(allocator));
+}
+
+template<is_object T, allocator Allocator = DefaultAllocator, typename... Args>
+constexpr box<T, Allocator> make_box(Args&&... args)
+ requires default_constructible<Allocator> && constructible_from<T, Args&&...>
+{
+ Allocator allocator{};
+ void* raw_ptr = allocator.alloc(layout::of<T>());
+ T* ptr = new (raw_ptr) T{ ASL_FWD(args)... };
+ return box<T>(ptr, ASL_MOVE(allocator));
+}
+
} // namespace asl
|