Cogs.Core
Allocator.h
1#pragma once
2
3
4#include "../FoundationBase.h"
5#include "../Platform/Atomic.h"
6
7#include <OsoMemoryProfiler/CogsMemoryProfile.h>
8
9#ifndef _WIN32
10#include <utility>
11#endif
12
13namespace Cogs {
14 namespace Memory {
15#ifdef EMSCRIPTEN
16 constexpr size_t kDefaultAlignment = 8;
17#else
18 // For MSVC/GCC/Clang on Windows/Linux
19#if defined(_M_X64) || defined(__amd64__)
20 constexpr size_t kDefaultAlignment = 16;
21#else
22 constexpr size_t kDefaultAlignment = 8;
23#endif
24#endif
25
29 class COGSFOUNDATION_API Allocator
30 {
31 public:
32 Allocator() = default;
33 virtual ~Allocator() = default;
34
36 static Allocator * defaultAllocator();
37
40 static Allocator * overflowAllocator();
41
50 virtual void * allocate(size_t size, size_t alignment = 0, MemBlockType type = MemBlockType::Block);
51
60 virtual void deallocate(void * ptr, size_t size, MemBlockType type = MemBlockType::Block);
61
62 virtual void changeType(void* ptr, size_t size, MemBlockType oldType, MemBlockType newType);
63
65 virtual size_t getAllocatedBytes() const { return allocated; }
66
68 virtual size_t getAllocationCount() const { return allocations; }
69
70 protected:
71 Cogs::Atomic<size_t> allocated{0};
72 Cogs::Atomic<size_t> allocations{0};
73 };
74
82 template<typename T>
83 T * create(Allocator * allocator)
84 {
85 void * memory = allocator->allocate(sizeof(T), alignof(T));
86
87 return new (memory) T();
88 }
89
100 template<typename T, typename... Args>
101 T * create(Allocator * allocator, Args&&... args)
102 {
103 void * memory = allocator->allocate(sizeof(T), alignof(T));
104
105 return new (memory) T(std::forward<Args>(args)...);
106 }
107
116 template<typename T>
117 void destroy(T * t, Allocator * allocator)
118 {
119 t->~T();
120
121 allocator->deallocate(t, sizeof(T));
122 }
123 }
124}
Base allocator implementation.
Definition: Allocator.h:30
virtual size_t getAllocatedBytes() const
Return the number of bytes currently allocated by this allocator.
Definition: Allocator.h:65
virtual size_t getAllocationCount() const
Return the number of allocations currently allocated by this allocator.
Definition: Allocator.h:68
Contains all Cogs related functionality.
Definition: FieldSetter.h:23