Double checked locking
Hi,
I have a question on the double checked locking. The classic
implementation (shamelessly copied from Scott Meyers' and Andrei
Alexandrescu's article)
class Singleton {
public:
static Singleton* instance();
....
private:
static Singleton* pInstance;
};
Singleton* Singleton::instance() {
if (pInstance == 0) { // 1st test
Lock lock;
if (pInstance == 0) { // 2nd test
pInstance = new Singleton;
}
}
return pInstance;
}
is unsafe as there is no guarantee that the assignment of pInstance is
done after the constructor of Singleton is completed (http://
www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf).
However, if instead of the simple assignment one would use something
like:
void assign(Singleton*& to, Singleton* from){
to = from;
}
assign(pInstance, new Singleton);
would this become safe?
As far as I know, the standard requires all the parameters passed to a
function to be evaluated before the function is being called. Would
the memory allocation (without the call to the constructor) be
considered "enough" by an optimizing compiler so that the pointer
returned by it is passed to the assign function before the constructor
call is completed?
Regards,
Claudiu