DelegateMQ
Loading...
Searching...
No Matches
xallocator.h
Go to the documentation of this file.
1#ifndef _XALLOCATOR_H
2#define _XALLOCATOR_H
3
4#include <cstdint>
5#include <stddef.h>
6
7// @see https://github.com/endurodave/xallocator
8// David Lafreniere
9
10#ifdef __cplusplus
11// Define AUTOMATIC_XALLOCATOR_INIT_DESTROY to automatically call xalloc_init() and
12// xalloc_destroy() when using xallocator in C++ projects. On embedded systems that
13// never exit, you can save 1-byte of RAM storage per translation unit by undefining
14// AUTOMATIC_XALLOCATOR_INIT_DESTROY and calling xalloc_init() manually before the OS
15// starts.
16#define AUTOMATIC_XALLOCATOR_INIT_DESTROY
17#ifdef AUTOMATIC_XALLOCATOR_INIT_DESTROY
25class XallocInitDestroy
26{
27public:
28 XallocInitDestroy();
29 ~XallocInitDestroy();
30private:
31 static int32_t refCount;
32};
33static XallocInitDestroy xallocInitDestroy;
34#endif // AUTOMATIC_XALLOCATOR_INIT_DESTROY
35#endif // __cplusplus
36
37#ifdef __cplusplus
38extern "C" {
39#endif
40
48void xalloc_init();
49
55void xalloc_destroy();
56
59void *xmalloc(size_t size);
60
63void xfree(void* ptr);
64
68void *xrealloc(void *ptr, size_t size);
69
71void xalloc_stats();
72
73#ifdef DMQ_ALLOCATOR
74 // Macro to overload new/delete with xalloc/xfree. Add macro to any class to enable
75 // fixed-block memory allocation. Add to a base class provides fixed-block memory
76 // for the base and all derived classes.
77 //
78 // While std::make_shared is usually recommended for standard C++, in a fixed-block
79 // memory architecture, explicit 'new' is required to trigger the overloaded operator.
80 //
81 // Example:
82 // class MyMsg {
83 // XALLOCATOR
84 // };
85 //
86 // // BAD: Allocates global memory (Bypasses XALLOCATOR)
87 // auto msg = std::make_shared<MyMsg>();
88 //
89 // // GOOD: Allocates fixed-block memory (Uses XALLOCATOR)
90 // std::shared_ptr<MyMsg> msg(new MyMsg());
91 #define XALLOCATOR \
92 public: \
93 void* operator new(size_t size) { \
94 return xmalloc(size); \
95 } \
96 void* operator new(size_t size, void* mem) { \
97 return mem; \
98 } \
99 void* operator new(size_t size, const std::nothrow_t& nt) { \
100 return xmalloc(size); \
101 } \
102 void* operator new[](size_t size) { \
103 return xmalloc(size); \
104 } \
105 void operator delete(void* pObject) { \
106 xfree(pObject); \
107 } \
108 void operator delete(void* pObject, const std::nothrow_t& nt) { \
109 xfree(pObject); \
110 } \
111 void operator delete[](void* pData) { \
112 xfree(pData); \
113 }
114#endif
115
116#ifdef __cplusplus
117}
118#endif
119
120#endif
void xalloc_init()
Definition xallocator.cpp:193
void xfree(void *ptr)
Definition xallocator.cpp:326
void xalloc_stats()
Output allocator statistics to the standard output.
Definition xallocator.cpp:382
void xalloc_destroy()
Definition xallocator.cpp:234
void * xrealloc(void *ptr, size_t size)
Definition xallocator.cpp:348
void * xmalloc(size_t size)
Definition xallocator.cpp:301