Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You are correct that static initialization like that isn't thread safe (<a href="http://www.tilander.org/aurora2/Static_initialization_in_Cpp/index.html" rel="nofollow noreferrer">here</a> is an article discussing what the compiler will turn it into)</p> <p>At the moment, there's no standard, thread safe, portable way to initialize static singletons. Double checked locking can be used, but you need potentially non-portable threading libraries (see a discussion <a href="http://www.devarticles.com/c/a/Cplusplus/C-plus-in-Theory-Why-the-Double-Check-Lock-Pattern-Isnt-100-ThreadSafe/3/" rel="nofollow noreferrer">here</a>).</p> <p>Here's a few options if thread safety is a must:</p> <ol> <li>Don't be Lazy (loaded): Initialize during static initialization. It could be a problem if another static calls this function in it's constructor, since the order of static initialization is undefined(see <a href="https://isocpp.org/wiki/faq/ctors#static-init-order" rel="nofollow noreferrer">here</a>).</li> <li>Use boost (as you said) or Loki</li> <li>Roll your own singleton on your supported platforms (should probably be avoided unless you are a threading expert)</li> <li>Lock a mutex everytime you need access. This could be very slow.</li> </ol> <p>Example for 1:</p> <pre><code>// in a cpp: namespace { Dog dog("Lassie"); } Dog* MyClass::BadMethod() { return &amp;dog; } </code></pre> <p>Example for 4:</p> <pre><code>Dog* MyClass::BadMethod() { static scoped_ptr&lt;Dog&gt; pdog; { Lock l(Mutex); if(!pdog.get()) pdog.reset(new Dog("Lassie")); } return pdog.get(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload