Date: Sat, 17 Nov 2012 13:51:48 +0100 From: "Vicente J. Botet Escriba"
Hi, your code suffers from the problem you try to avoid "But we all know this is not thread safe, at least for the first call" at least in c++98 as you are using static variables. Actually, my post described the circumstances under which it does in fact work: when VarType has a built-in type that is initialized before program execution, or on C++11 with a constexpr constructor.
here they are some pointers that while not responding exactly to your question them could help you.
http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-par... Interesting, the post gets it wrong. A unique_ptr has a constructor (in C++03) so still has the problem. Or, maybe the article is just not clear on how it is to be used: if you must initialize an instance of lazy_init (to the null pointer internally) _before_ multiple threads ask it to be "initialized", that just pushes the problem back to the earlier step. I can see the usefulness though, if you just want to put off the expensive "real" initialization until needed, but can arrange the pre-initialization to be done for-sure earlier.
http://stackoverflow.com/questions/12302057/c11-safe-double-checked-locking-...
This points out that under C++11 rules, static locals are thread safe for the first-time initialization. That explains why there is no fancy construct for doing so; it's just there! Nice. Or it will be, some day. I looked at the code generated by Microsoft VS2010 and it does not give this feature, alas. It does tell me though that a compatibility construct like I'm looking for ought to expand into a plain static local for compilers that do work that way; just let the compiler do it. All the more reason to abstract the issue for current uses! —John