Allocator: add MEM_cnew_array

This is a more C++ friendly version MEM_calloc_arrayN, like MEM_cnew is for
MEM_callocN. For cases where data structures are still C and Vector or Array
don't work.
This commit is contained in:
Brecht Van Lommel 2022-08-26 18:09:44 +02:00
parent 658ff994c5
commit ff27457240
1 changed files with 27 additions and 16 deletions

View File

@ -275,6 +275,21 @@ inline T *MEM_new(const char *allocation_name, Args &&...args)
return new (buffer) T(std::forward<Args>(args)...);
}
/**
* Destructs and deallocates an object previously allocated with any `MEM_*` function.
* Passing in null does nothing.
*/
template<typename T> inline void MEM_delete(const T *ptr)
{
if (ptr == nullptr) {
/* Support #ptr being null, because C++ `delete` supports that as well. */
return;
}
/* C++ allows destruction of const objects, so the pointer is allowed to be const. */
ptr->~T();
MEM_freeN(const_cast<T *>(ptr));
}
/**
* Allocates zero-initialized memory for an object of type #T. The constructor of #T is not called,
* therefor this should only used with trivial types (like all C types).
@ -287,6 +302,15 @@ template<typename T> inline T *MEM_cnew(const char *allocation_name)
return static_cast<T *>(MEM_callocN(sizeof(T), allocation_name));
}
/**
* Same as MEM_cnew but for arrays, better alternative to #MEM_calloc_arrayN.
*/
template<typename T> inline T *MEM_cnew_array(const size_t length, const char *allocation_name)
{
static_assert(std::is_trivial_v<T>, "For non-trivial types, MEM_new should be used.");
return static_cast<T *>(MEM_calloc_arrayN(length, sizeof(T), allocation_name));
}
/**
* Allocate memory for an object of type #T and copy construct an object from `other`.
* Only applicable for a trivial types.
@ -301,23 +325,10 @@ template<typename T> inline T *MEM_cnew(const char *allocation_name, const T &ot
{
static_assert(std::is_trivial_v<T>, "For non-trivial types, MEM_new should be used.");
T *new_object = static_cast<T *>(MEM_mallocN(sizeof(T), allocation_name));
memcpy(new_object, &other, sizeof(T));
return new_object;
}
/**
* Destructs and deallocates an object previously allocated with any `MEM_*` function.
* Passing in null does nothing.
*/
template<typename T> inline void MEM_delete(const T *ptr)
{
if (ptr == nullptr) {
/* Support #ptr being null, because C++ `delete` supports that as well. */
return;
if (new_object) {
memcpy(new_object, &other, sizeof(T));
}
/* C++ allows destruction of const objects, so the pointer is allowed to be const. */
ptr->~T();
MEM_freeN(const_cast<T *>(ptr));
return new_object;
}
/* Allocation functions (for C++ only). */