1

I have the following class:

struct globalAllocated 
{
    void operator delete(void*p)
    {
        static HANDLE heap= GetHeap();
        ::HeapFree(heap, 0, p);
    }
}

warning C4640: 'heap' : construction of local static object is not thread-safe

I thought about using some synchronization with mutex but it seems costly.

Making the heap a private member won't work because the operator delete override must be static, so heap must be private- but if I declare it as a static class member, there is no where for me to initialize it.

What's the best solution?

Borgleader
  • 15,826
  • 5
  • 46
  • 62
damule
  • 235
  • 1
  • 8
  • “but if I declare it as a static class member, there is no where for me to initialize it.” – [yes there is](http://stackoverflow.com/q/185844/1968). – Konrad Rudolph Jan 26 '15 at 15:44
  • you'll probably need to make HeapFree thread-safe anyway. At that point, there wouldn't necessarily be an extra cost making 'delete' thread-safe – Come Raczy Jan 26 '15 at 15:50
  • There is no cpp file. This isn't c++11. The class will be used as a parameter to a template as a custom allocator, so no one will actually call it explicitly. – damule Jan 26 '15 at 16:40

1 Answers1

3

If you can use C++11, it's required to be thread-safe there. (But that could easily be implemented by using a mutex as well, if you're concerned about performance issues.)

More generally: try to ensure that the function is called before multiple threads are started. (In many applications, all that is needed is to call it somewhere in the initialization of a static object.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329