2021-08-21 08:29:58 +00:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <cassert>
|
|
|
|
#include <cstddef>
|
|
|
|
#include <memory>
|
|
|
|
|
|
|
|
|
|
|
|
namespace gj {
|
|
|
|
|
|
|
|
|
|
|
|
class iAllocator {
|
|
|
|
public:
|
|
|
|
template <typename T>
|
|
|
|
struct Deleter {
|
|
|
|
Deleter() = default;
|
|
|
|
Deleter(Deleter&&) = default;
|
|
|
|
Deleter(const Deleter&) = delete;
|
|
|
|
|
|
|
|
Deleter& operator=(Deleter&&) = default;
|
|
|
|
Deleter& operator=(const Deleter&) = delete;
|
|
|
|
|
|
|
|
Deleter(iAllocator* alloc) : alloc_(alloc) {
|
|
|
|
}
|
|
|
|
|
|
|
|
void operator()(T* ptr) {
|
|
|
|
assert(alloc_);
|
|
|
|
ptr->~T();
|
|
|
|
alloc_->Free(ptr);
|
|
|
|
}
|
|
|
|
|
|
|
|
iAllocator* alloc_;
|
|
|
|
};
|
|
|
|
|
|
|
|
template <typename T>
|
2021-08-25 03:27:39 +00:00
|
|
|
using UniqPtr = std::unique_ptr<T, iAllocator::Deleter<T>>;
|
2021-08-21 08:29:58 +00:00
|
|
|
|
2021-08-23 09:25:44 +00:00
|
|
|
iAllocator(iAllocator&&) = default;
|
|
|
|
iAllocator(const iAllocator&) = default;
|
2021-08-21 08:29:58 +00:00
|
|
|
|
2021-08-23 09:25:44 +00:00
|
|
|
iAllocator& operator=(iAllocator&&) = default;
|
|
|
|
iAllocator& operator=(const iAllocator&) = default;
|
2021-08-21 08:29:58 +00:00
|
|
|
|
|
|
|
iAllocator() = default;
|
|
|
|
|
|
|
|
virtual ~iAllocator() = default;
|
|
|
|
|
|
|
|
virtual void* Alloc(const size_t size) = 0;
|
|
|
|
virtual void Free(void* ptr) = 0;
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
T* Alloc(size_t n = 1) {
|
|
|
|
return reinterpret_cast<T*>(Alloc(sizeof(T) * n));
|
|
|
|
}
|
|
|
|
|
|
|
|
template <typename T, typename... Args>
|
2021-08-25 03:27:39 +00:00
|
|
|
UniqPtr<T> MakeUniq(Args&&... args) {
|
2021-08-21 08:29:58 +00:00
|
|
|
T* ptr = Alloc<T>();
|
2021-08-25 03:27:39 +00:00
|
|
|
return std::unique_ptr<T, Deleter<T>>(new(ptr) T(std::forward<Args>(args)...), Deleter<T>(this));
|
|
|
|
}
|
|
|
|
template <typename I, typename T, typename... Args>
|
|
|
|
UniqPtr<I> MakeUniq(Args&&... args) {
|
|
|
|
T* ptr = Alloc<T>();
|
|
|
|
return std::unique_ptr<I, Deleter<I>>(new(ptr) T(std::forward<Args>(args)...), Deleter<I>(this));
|
2021-08-21 08:29:58 +00:00
|
|
|
}
|
|
|
|
template <typename T>
|
2021-08-25 03:27:39 +00:00
|
|
|
UniqPtr<T> MakeUniqArray(size_t n) {
|
2021-08-21 08:29:58 +00:00
|
|
|
T* ptr = Alloc<T>(n);
|
|
|
|
return std::unique_ptr<T, Deleter<T>>(ptr, Deleter<T>(this));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-08-25 03:27:39 +00:00
|
|
|
template <typename T>
|
|
|
|
using UniqPtr = iAllocator::UniqPtr<T>;
|
|
|
|
|
2021-08-21 08:29:58 +00:00
|
|
|
|
|
|
|
}
|