Global static variable not initialized before overloaded global new() call in C++
<p>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):</p>

<pre><code>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;
}
</code></pre>

<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.</p>

<p>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:</p>

<pre><code>HeapManager* pheapManager = NULL;    

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

<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.</p>
