使用编译器强制第一个实例

Force first instance with compiler

本文关键字:第一个 实例 编译器      更新时间:2023-10-16

我们已经制作了一个覆盖new()delete()运算符的主存储堆内存管理器,但是存在一个问题,因为我们需要在任何其他内存分配发生之前启动内存管理器 - 如果我们不这样做,那么进程将包含一些非托管内存。到目前为止的解决方案是在具有main()功能的同一文件中启动内存管理器,如下所示:

/*!
brief Start the memory manager. 
note It's important that this is causing the very first call to the overridden new() operator.
*/
CMemoryManager *g_memoryManager = CMemoryManager::Instance();
int main(int argc, char* argv[])
{
    // Code...
}

这有效但不是最佳的,因为我们在每个可执行文件(如每个单元测试)中都需要它,因为内存管理器是一种横切关注类型的功能。对我们来说,最好的方法是将内存管理器启动放在单个库中,并确保首先执行该库 - 因此我们不必将启动添加到每个可执行文件中。有没有办法使用 G++、VC++ 和 ICC 编译器来做到这一点?

/**
 * defgroup MemoryManagerMutexes Uniform mutex definitions for use with the memory manager
 */
/*@{*/
#ifdef _WINDOWS
#define MM_INIT_CRITICAL_SECTION(arg1) InitializeCriticalSection(&arg1);
#define MM_DELETE_CRITICAL_SECTION(arg1) DeleteCriticalSection(&arg1);
#define MM_ENTER_CRITICAL_SECTION(arg1) EnterCriticalSection(&arg1);
#define MM_LEAVE_CRITICAL_SECTION(arg1) LeaveCriticalSection(&arg1);
#define MM_CRITICAL_SECTION_OBJECT(arg1) CRITICAL_SECTION arg1;
#else
#ifdef HAVE_PTHREAD_H
#define MM_INIT_CRITICAL_SECTION(arg1) pthread_mutex_init(&arg1, NULL);
#define MM_DELETE_CRITICAL_SECTION(arg1) pthread_mutex_destroy(&arg1);
#define MM_ENTER_CRITICAL_SECTION(arg1) pthread_mutex_lock(&arg1);
#define MM_LEAVE_CRITICAL_SECTION(arg1) pthread_mutex_unlock(&arg1);
#define MM_CRITICAL_SECTION_OBJECT(arg1) pthread_mutex_t arg1;
#else
#error Neither Windows nor POSIX mutex libraries were found and no fallback
#endif
#endif
/*@}*/
/*!
brief Get the instance of the memory manager
details Class uses a Singleton software design pattern
returns The instance of the memory manager
*/
CMemoryManager *CMemoryManager::Instance()
{
    if (!instance)
    { 
        MM_INIT_CRITICAL_SECTION(mutex)
        instance = new CMemoryManager();
    }
    return instance;
}
// Non-TLS new() implementation
void *operator new(size_t size) 
{
    MM_ENTER_CRITICAL_SECTION(CMemoryManager::mutex)
    void *ret = CMemoryManager::Instance()->Malloc(size);
    MM_LEAVE_CRITICAL_SECTION(CMemoryManager::mutex)
return ret;
}

更改标头中的实例例程

static Instance(bool first=false);

在定义中

CMemoryManager *CMemoryManager::Instance(bool first)
{
    if (!instance)
    {
        if (first)
       { 
            MM_INIT_CRITICAL_SECTION(mutex)
            instance = new CMemoryManager();
       }
       else
       {
           do {
               sleep(0);
           } while (!instance);
       }
    }
    return instance;
}

您将需要某种睡眠程序。在主

CMemoryManager *g_memoryManager = CMemoryManager::Instance(true);
相关文章: