Add templated CHeap::Allocate function

Add a templated `CHeap::Allocate` function to simplify memory allocation of objects using `CHeap`. The function uses perfect forwarding to construct objects with the specified arguments.
This commit is contained in:
Robert Müller 2023-11-22 23:51:06 +01:00
parent 3e2f8f8a44
commit 41d2c80f21
4 changed files with 13 additions and 3 deletions

View file

@ -657,7 +657,7 @@ void CServerBrowser::SetLatency(NETADDR Addr, int Latency)
CServerBrowser::CServerEntry *CServerBrowser::Add(const NETADDR *pAddrs, int NumAddrs)
{
// create new pEntry
CServerEntry *pEntry = (CServerEntry *)m_ServerlistHeap.Allocate(sizeof(CServerEntry));
CServerEntry *pEntry = m_ServerlistHeap.Allocate<CServerEntry>();
mem_zero(pEntry, sizeof(CServerEntry));
// set the info

View file

@ -172,7 +172,7 @@ class CConsole : public IConsole
void AddEntry()
{
CQueueEntry *pEntry = static_cast<CQueueEntry *>(m_Queue.Allocate(sizeof(CQueueEntry)));
CQueueEntry *pEntry = m_Queue.Allocate<CQueueEntry>();
pEntry->m_pNext = 0;
if(!m_pFirst)
m_pFirst = pEntry;

View file

@ -4,6 +4,9 @@
#define ENGINE_SHARED_MEMHEAP_H
#include <cstddef>
#include <new>
#include <utility>
class CHeap
{
struct CChunk
@ -32,5 +35,12 @@ public:
void Reset();
void *Allocate(unsigned Size, unsigned Alignment = alignof(std::max_align_t));
const char *StoreString(const char *pSrc);
template<typename T, typename... TArgs>
T *Allocate(TArgs &&... Args)
{
return new(Allocate(sizeof(T), alignof(T))) T(std::forward<TArgs>(Args)...);
}
};
#endif

View file

@ -163,7 +163,7 @@ void CVoting::AddOption(const char *pDescription)
m_pRecycleLast = 0;
}
else
pOption = (CVoteOptionClient *)m_Heap.Allocate(sizeof(CVoteOptionClient));
pOption = m_Heap.Allocate<CVoteOptionClient>();
pOption->m_pNext = 0;
pOption->m_pPrev = m_pLast;