我很好奇下面的代码:函数中的静态对象是否引入潜在的竞争条件?
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;
[...]
}
有没有在上面的代码中可能的竞争条件?具体来说,编译器是否可能生成等同于以下内容的代码,“幕后”?
void MyFunction()
{
static bool _myClassObjectInitialized = false;
if (_myClassObjectInitialized == false)
{
_myClassObjectInitialized = true;
_myClassObject.MyClass(); // call constructor to set up object
}
[...]
}
...在这种情况下,如果两个线程都调用MyFunction的()几乎同时地,然后_myArray可能会分配两次,导致内存泄漏?
或者这是否正确处理?
许多受骗者包括http://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-ac-function – 2010-05-30 17:12:55
的这大概也与此有关:HTTP:/ /stackoverflow.com/questions/1661529/is-meyers-implementation-of-singleton-pattern-thread-safe – 2010-05-30 19:46:57