简体   繁体   English

在C ++中重载全局new()之前未初始化全局静态变量

[英]Global static variable not initialized before overloaded global new() call in C++

In one project I have globally overloaded operator new/delete to make use of a private heap. 在一个项目中,我全局重载了运算符new / delete以使用私有堆。 The code that does this goes like (in file Allocator.cpp): 执行此操作的代码如下所示(在文件Allocator.cpp中):

static HeapManager heapManager;

void * operator new (size_t size)  
{
    void * p = heapManager.AllocateFromHeap(size);
      if (p == 0) // did malloc succeed?
            throw std::bad_alloc(); // ANSI/ISO compliant behavior  
        return p;
}

The goal was that heapManager will be initialized when the file is loaded and then when somebody calls new(), memory will be allocated from heap. 目的是在加载文件时初始化heapManager,然后当有人调用new()时,将从堆中分配内存。 This code is packed in a dll and used by another exe. 此代码打包在dll中,并由另一个exe使用。

But what we found was that somebody outside our dll code was calling new() and the heapManager was null. 但是我们发现,在dll代码之外的某个人正在调用new(),并且heapManager为null。 We solved the problem like this: 我们解决了这样的问题:

HeapManager* pheapManager = NULL;    

void * operator new (size_t size)  
{
    static HeapManager heapManager;
    if (pheapManager == NULL)
    {
        pheapManager = &heapManager;
    }
    void * p = pheapManager->AllocateFromHeap(size);
    if (p == 0) // did malloc succeed?
        throw std::bad_alloc(); // ANSI/ISO compliant behavior  
    return p;
}

But his looks ugly. 但是他的长相难看。 Is there any better way to solve this? 有没有更好的方法来解决这个问题? All I want is to make sure that the static HeapManager variable is initialized before new() is called. 我想要做的就是确保在调用new()之前初始化静态HeapManager变量。

Hide it in a function: 将其隐藏在函数中:

HeapManager& getHeapManager()
{
    static HeapManager single;
    return single;
}

// ...

void * operator new ( ... )
{
    void* p = getHeapmanager().AllocateFromHeap( size );
    ...

This way it'll be created only when function is called. 这样,只有在调用函数时才能创建它。

Check out the The Nifty Counter Trick. 查看《 The Nifty Counter Trick》。 That's the trick used to make cout and cerr globals: http://www.petebecker.com/js/js199905.html 这就是使cout和cerr成为全局变量的技巧: http ://www.petebecker.com/js/js199905.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM