Memory.h fixes

* Use a Nifty Counter for rpmalloc initialization. This fixes init order
  with other static objects using MmAllocator or MemoryManagger
* Fix exception throwing in AlignedAllocator
* Add missing constructor to MmAllocator for compatibility with std
  containers
This commit is contained in:
Lukas W
2018-04-15 21:45:30 +02:00
parent 3c73270c23
commit 1340c273c7
4 changed files with 120 additions and 41 deletions

View File

@@ -1,7 +1,7 @@
/*
* MemoryManager.cpp
* Memory.cpp
*
* Copyright (c) 2017 Lukas W <lukaswhl/at/gmail.com>
* Copyright (c) 2018 Lukas W <lukaswhl/at/gmail.com>
* Copyright (c) 2014 Simon Symeonidis <lethaljellybean/at/gmail/com>
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
@@ -30,35 +30,6 @@
#include <QtCore/QtGlobal>
#include "rpmalloc.h"
/// Global static object handling rpmalloc intializing and finalizing
struct MemoryManagerGlobalGuard {
MemoryManagerGlobalGuard() {
rpmalloc_initialize();
}
~MemoryManagerGlobalGuard() {
rpmalloc_finalize();
}
} static mm_global_guard;
namespace {
static thread_local size_t thread_guard_depth;
}
MemoryManager::ThreadGuard::ThreadGuard()
{
if (thread_guard_depth++ == 0) {
rpmalloc_thread_initialize();
}
}
MemoryManager::ThreadGuard::~ThreadGuard()
{
if (--thread_guard_depth == 0) {
rpmalloc_thread_finalize();
}
}
static thread_local MemoryManager::ThreadGuard local_mm_thread_guard{};
void* MemoryManager::alloc(size_t size)
@@ -78,6 +49,26 @@ void MemoryManager::free(void * ptr)
return rpfree(ptr);
}
void MemoryManager::initialize()
{
rpmalloc_initialize();
}
void MemoryManager::deinitialize()
{
rpmalloc_finalize();
}
void MemoryManager::thread_initialize()
{
rpmalloc_thread_initialize();
}
void MemoryManager::thread_deinitialize()
{
rpmalloc_thread_finalize();
}
void* _AlignedAllocator_Base::alloc_impl( size_t n , size_t alignment)
{
char *ptr, *ptr2, *aligned_ptr;
@@ -85,7 +76,7 @@ void* _AlignedAllocator_Base::alloc_impl( size_t n , size_t alignment)
ptr = static_cast<char*>( malloc( n + alignment + sizeof( int ) ) );
if( ptr == NULL ) std::bad_alloc;
if( ptr == NULL ) throw std::bad_alloc{};
ptr2 = ptr + sizeof( int );
aligned_ptr = ptr2 + ( alignment - ( ( size_t ) ptr2 & align_mask ) );