Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are no threads in your example. Assuming there are more objects initialized during static initialization which may be spawning threads and access <code>singleton::ref</code>, the code is prone to access uninitialized memory and it isn't thread-safe. If the first thread is started after entering <code>main()</code> the code is thread-safe.</p> <p>In case you want to make sure the object is properly constructed upon first access and, at the same time, make the construction thread-safe even when accessed during static initialization from multiple threads, you'd use</p> <pre><code>singleton* singleton::getInstance() { static singleton rc; return &amp;rc; } </code></pre> <p>The relevant section in the standard which guarantees that the above is thread safe is 6.7 [stmt.dcl] paragraph 4:</p> <blockquote> <p>... If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization ...</p> </blockquote> <p>The object would be constructed the first time <code>getInstance()</code> is called. Even if multiple threads concurrently call <code>getInstance()</code> the object will be constructed only once and the concurrent calls to <code>getInstance()</code> will block until construction is complete. You can make sure that the construction of <code>getInstance()</code> happens during static initialization by using it in the implementation of <code>singleton</code>:</p> <pre><code>static singleton* constructionDummy = singleton::getInstance(); </code></pre> <p>Note that singletons generally cause major problems, doubly so in multi-threaded programs. In addition to the problems singletons already create in single-threaded programs they further introduce the potential for data races and, in an attempt to address the data races, tend to introduce serialization. With the possible exception of singletons which set up strictly immutable data I recommend to <strong>not</strong> use them.</p>
 

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