Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are two things going on here:</p> <ul> <li>What if the user would dearly like to parallelize her code ?</li> <li>What if the user would like to start using your library during the static initialization phase ?</li> </ul> <p>So, one at a time.</p> <p><em>1. What if the user would dearly like to parallelize her code ?</em></p> <p>In the age of multi-core processors libraries should strive for re-entrancy. <strong>Global State</strong> is bad, and <strong>unsynchronized</strong> Global State is even worse.</p> <p>I would simply recommend for you to make <code>Foo</code> contain regular attributes instead of <code>static</code> ones, it is then up to the user to decide how many instances in parallel should be used, and perhaps settle on one.</p> <p>If passing a <code>Foo</code> to all your methods would prove awkward, have a look at the <code>Facade</code> pattern. The idea here would be to create a <code>Facade</code> class that is initialized with a <code>Foo</code> and provides entry points to your library.</p> <p><em>2. What if the user would like to start using your library during the static initialization phase ?</em></p> <p>The static initialization order fiasco is just horrid, and the static destruction order fiasco (its sibling) is no better, and even harder to track down (because the memory is not 0-initialized there, so it's hard to see what's going on).</p> <p>Since once again it's hard (impossible ?) for you to predict the usage of your library and since any attempt to use it during static initialization or destruction is nigh impossible with a singleton that you would create, the simpler thing to do is to delegate at least initialization to the user.</p> <p>If the user is unlikely to be willing to use this library at start-up and shut-down, then you may provide a simple safeguard to automatically initialize the library on first use if she didn't already.</p> <p>This can be accomplished easily, and in a thread-safe manner (*), using local static variables:</p> <pre><code>class Foo { public: static Foo&amp; Init() { static Foo foo; return foo; } static int GetValue() { return Init()._value; } private: Foo(): _value(1) {} Foo(Foo const&amp;) = delete; Foo&amp; operator=(Foo const&amp;) = delete; int _value; }; // class Foo </code></pre> <p>Note that all this glue is completely useless if you simply decide <em>not</em> to use a Singleton and go for the first solution: a regular object, with per-instance state only.</p> <p>(*) Thread safety is guaranteed in C++11. In C++03 (the version used primarily in the industry) the best compilers guarantee it as well, check the documentation if required.</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