From 41d2c80f21296f8c82063fbe0d43714ce70ffda2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20M=C3=BCller?= Date: Wed, 22 Nov 2023 23:51:06 +0100 Subject: [PATCH] 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. --- src/engine/client/serverbrowser.cpp | 2 +- src/engine/shared/console.h | 2 +- src/engine/shared/memheap.h | 10 ++++++++++ src/game/client/components/voting.cpp | 2 +- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/engine/client/serverbrowser.cpp b/src/engine/client/serverbrowser.cpp index 2b649ef5f..236f9d6c3 100644 --- a/src/engine/client/serverbrowser.cpp +++ b/src/engine/client/serverbrowser.cpp @@ -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(); mem_zero(pEntry, sizeof(CServerEntry)); // set the info diff --git a/src/engine/shared/console.h b/src/engine/shared/console.h index 614dd0e0c..d16770c46 100644 --- a/src/engine/shared/console.h +++ b/src/engine/shared/console.h @@ -172,7 +172,7 @@ class CConsole : public IConsole void AddEntry() { - CQueueEntry *pEntry = static_cast(m_Queue.Allocate(sizeof(CQueueEntry))); + CQueueEntry *pEntry = m_Queue.Allocate(); pEntry->m_pNext = 0; if(!m_pFirst) m_pFirst = pEntry; diff --git a/src/engine/shared/memheap.h b/src/engine/shared/memheap.h index 2d44dab46..acabfa623 100644 --- a/src/engine/shared/memheap.h +++ b/src/engine/shared/memheap.h @@ -4,6 +4,9 @@ #define ENGINE_SHARED_MEMHEAP_H #include +#include +#include + 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 + T *Allocate(TArgs &&... Args) + { + return new(Allocate(sizeof(T), alignof(T))) T(std::forward(Args)...); + } }; + #endif diff --git a/src/game/client/components/voting.cpp b/src/game/client/components/voting.cpp index 21242a9d5..aaab39ded 100644 --- a/src/game/client/components/voting.cpp +++ b/src/game/client/components/voting.cpp @@ -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(); pOption->m_pNext = 0; pOption->m_pPrev = m_pLast;