zengine/engine/modules/engine/zlib/include/pmr/frame_allocator.h
2024-07-24 14:42:14 +08:00

49 lines
2.1 KiB
C++

#pragma once
#include <vector>
#include <memory_resource>
namespace pmr {
class FrameAllocator : public std::pmr::memory_resource {
private:
char* buffer;
size_t capacity;
size_t offset;
public:
// 删除拷贝构造函数
FrameAllocator(const FrameAllocator&) = delete;
FrameAllocator& operator=(const FrameAllocator&) = delete;
FrameAllocator(FrameAllocator&& o) noexcept;
FrameAllocator& operator=(FrameAllocator&& o)noexcept;
public:
FrameAllocator(size_t size) noexcept;
~FrameAllocator() noexcept;
bool empty() const { return offset == 0; }
void reset() { offset = 0; };
void* try_allocate(size_t bytes, size_t alignment);
protected:
void move_clear() { buffer = nullptr; capacity = 0; offset = 0; };
void* do_allocate(size_t bytes, size_t alignment) override;
void do_deallocate(void* p, size_t bytes, size_t alignment) override {};
bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { return this == &other; };
};
class FrameAllocatorPool : public std::pmr::memory_resource {
public:
FrameAllocatorPool(size_t allocatorSize = 1024 * 1024) noexcept : allocatorSize(allocatorSize) {}
void* allocate(size_t bytes, size_t alignment);
void reset();
void* do_allocate(size_t bytes, size_t alignment) override { return allocate(bytes, alignment); }
void do_deallocate(void* p, size_t bytes, size_t alignment) override {};
bool do_is_equal(const std::pmr::memory_resource& other) const noexcept override { return this == &other; };
private:
size_t allocatorSize;
std::vector<FrameAllocator> allocators{};
};
};
// 自定义的new操作符
inline void* operator new(size_t size, pmr::FrameAllocatorPool& pool, size_t alignment = alignof(std::max_align_t)) {
size = (size + alignment - 1) & ~(alignment - 1);
return pool.allocate(size, alignment);
}
#include "frame_allocator.inl"
inline static pmr::FrameAllocatorPool MemPool{};
inline static pmr::FrameAllocatorPool FramePool{};