468,497 Members | 1,887 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,497 developers. It's quick & easy.

Double-Checked Locking pattern issue

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?

Expand|Select|Wrap|Line Numbers
  1.  
  2. Singleton* Singleton::instance() {
  3. if (pInstance == 0) {
  4. Lock lock;
  5. if (pInstance == 0) {
  6. pInstance = // Step 3
  7. operator new(sizeof(Singleton)); // Step 1
  8. new (pInstance) Singleton; // Step 2
  9. }
  10. }
  11. return pInstance;
  12. }
  13.  
  14.  

thanks in advance,
George
Dec 30 '07 #1
0 1004

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

31 posts views Thread by Bjørn Augestad | last post: by
10 posts views Thread by Robert Palma | last post: by
67 posts views Thread by lcw1964 | last post: by
11 posts views Thread by Ole Nielsby | last post: by
2 posts views Thread by dj10fld | last post: by
reply views Thread by NPC403 | last post: by
3 posts views Thread by gieforce | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.