开发者

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. The code that does this goes like (in file Allocator.cpp):

static HeapManager heapManager;

void * operator new (size_t size)  
{
    voi开发者_JAVA技巧d * 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. This code is packed in a dll and used by another exe.

But what we found was that somebody outside our dll code was calling new() and the heapManager was 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.


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. That's the trick used to make cout and cerr globals: http://www.petebecker.com/js/js199905.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜