Hello gurus,


For the wellknown Double-Checked Locking pattern,

http://www.ddj.com/184405726?pgno=1

Step 1: Allocate memory to hold a Singleton object.
Step 2: Construct a Singleton object in the allocated memory.
Step 3: Make pInstance point to the allocated memory.

After reading for a couple of times, I still do not understand why some compiler will exchange step 2 and step 3 code? If there are any exception in step 2, the swap code will make pInstance point to an invalid memory address. Any ideas why compiler do the swap?

Code:
Singleton* Singleton::instance() {
if (pInstance == 0) {
Lock lock;
if (pInstance == 0) {
pInstance = // Step 3
operator new(sizeof(Singleton)); // Step 1
new (pInstance) Singleton; // Step 2
}
}
return pInstance;
}

thanks in advance,
George