Does a static object within a function introduce a potential race condition?

Posted by Jeremy Friesner on Stack Overflow See other posts from Stack Overflow or by Jeremy Friesner
Published on 2010-05-30T17:09:47Z Indexed on 2010/05/30 17:12 UTC
Read the original article Hit count: 226

Filed under:
|
|

I'm curious about the following code:

class MyClass
{
public:
   MyClass() : _myArray(new int[1024]) {}
   ~MyClass() {delete [] _myArray;}

private:
   int * _myArray;
};

// This function may be called by different threads in an unsynchronized manner
void MyFunction()
{
   static const MyClass _myClassObject;
   [...]
}

Is there a possible race condition in the above code? Specifically, is the compiler likely to generate code equivalent to the following, "behind the scenes"?

void MyFunction()
{
   static bool _myClassObjectInitialized = false;
   if (_myClassObjectInitialized == false)
   {
      _myClassObjectInitialized = true;
      _myClassObject.MyClass();   // call constructor to set up object
   }
   [...]
}

... in which case, if two threads were to call MyFunction() nearly-simultaneously, then _myArray might get allocated twice, causing a memory leak?

Or is this handled correctly somehow?

© Stack Overflow or respective owner

Related posts about c++

Related posts about static