// license:BSD-3-Clause // copyright-holders:Aaron Giles /*************************************************************************** corealloc.h Memory allocation helpers for the helper library. ***************************************************************************/ #pragma once #ifndef MAME_LIB_UTIL_COREALLOC_H #define MAME_LIB_UTIL_COREALLOC_H #include "osdcore.h" #include #include #include #include #include #include #include //************************************************************************** // MACROS //************************************************************************** // global allocation helpers -- use these instead of new and delete #define global_alloc(Type) new Type #define global_alloc_nothrow(Type) new (std::nothrow) Type #define global_alloc_array(Type, Num) new Type[Num] #define global_alloc_array_nothrow(Type, Num) new (std::nothrow) Type[Num] #define global_free(Ptr) do { delete Ptr; } while (0) #define global_free_array(Ptr) do { delete[] Ptr; } while (0) template inline T* global_alloc_clear(Params &&... args) { void *const ptr = ::operator new(sizeof(T)); // allocate memory std::memset(ptr, 0, sizeof(T)); return new(ptr) T(std::forward(args)...); } template inline T* global_alloc_array_clear(std::size_t num) { auto const size = sizeof(T) * num; void *const ptr = new unsigned char[size]; // allocate memory std::memset(ptr, 0, size); return new(ptr) T[num](); } template struct MakeUniqClearT { typedef std::unique_ptr single_object; }; template struct MakeUniqClearT { typedef std::unique_ptr array; }; template struct MakeUniqClearT { struct invalid_type { }; }; /// make_unique_clear for single objects template inline typename MakeUniqClearT::single_object make_unique_clear(Params&&... args) { void *const ptr = ::operator new(sizeof(Tp)); // allocate memory std::memset(ptr, 0, sizeof(Tp)); return std::unique_ptr(new(ptr) Tp(std::forward(args)...)); } /// make_unique_clear for arrays of unknown bound template inline typename MakeUniqClearT::array make_unique_clear(size_t num) { auto size = sizeof(std::remove_extent_t) * num; unsigned char* ptr = new unsigned char[size]; // allocate memory std::memset(ptr, 0, size); return std::unique_ptr(new(ptr) std::remove_extent_t[num]()); } template inline typename MakeUniqClearT::array make_unique_clear(size_t num) { auto size = sizeof(std::remove_extent_t) * num; unsigned char* ptr = new unsigned char[size]; // allocate memory std::memset(ptr, F, size); return std::unique_ptr(new(ptr) std::remove_extent_t[num]()); } /// Disable make_unique_clear for arrays of known bound template inline typename MakeUniqClearT::invalid_type make_unique_clear(Params&&...) = delete; #endif // MAME_LIB_UTIL_COREALLOC_H