Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>In getInstance function (un-commented), static object's reference is returned. Does it requires thread-safe mechanism?</p> </blockquote> <p>As long as you don't access it outside the lifetime of the <code>main</code> function, or modify it when other threads might have unsynchronised access, then it's safe to access from any thread.</p> <p>If you do access before <code>main</code> starts or after it ends (e.g. from the constructor or destructor of another static object), then there is a danger that it won't have been initialised, or will already have been destroyed, at that point. That is the motivation for "lazy initialisation" such as your second version.</p> <blockquote> <p>In second getInstance (commented), we create the object if singleObject is null. So, it requires a locking mechanism and needs to be synchronized, right?</p> </blockquote> <p>Yes, that requires a locking mechanism. For compilers that support the C++11 (or similar) threading model, a simpler way to get lazy initialisation like this is to use a function-static variable, which will be initialised in a thread-safe way the first time it comes into scope:</p> <pre><code>S&amp; getInstance () { static S singleObject; return singleObject; } </code></pre> <p>This will also avoid the memory leak of your version, but introduces a danger that it might be destroyed before other static objects; therefore, it's not safe to access from a static object's destructor.</p> <p>In general, static objects in C++ are a minefield of such deathtraps (whether or not you try to wrap them up in some kind of singleton anti-pattern) and are best avoided.</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