Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The standard guarantees that static storage duration objects are initialized before any functions/variables in the same translation unit as your object are used from an external source.</p> <p>The wording here is designed to work with shared libraries. Because shared libraries can be dynamically loaded after main() has started the language specification has to be flexible enough to cope with it. But as long as you access your object from outside the translation unit then you are guaranteed that it will have been constructed before you are given accesses (unless you are doing something pathological).</p> <p><strong>BUT</strong> this does not stop it being used before initialization if it is used in the constructor of another static storage duration object in the same compilation unit.</p> <p>But you can easily manually provide guarantees that a static object is correctly initialized before used by using the technique below.</p> <p>Just change the static variable to a static function. Then inside the function declare a static member that is returned. So you can use it exactly the same way as before (just add <code>()</code>).</p> <pre><code>template &lt;class T&gt; struct PWrap_T { static P&amp; p_s(); // change static variable to static member function. // Rather than the type being P make it a reference to P // because the object will be held internally to the function }; template &lt;class T&gt; P&amp; PWrap_T&lt;T&gt;::p_s() { // Notice the member is static. // This means it will live longer than the function. // Also it will be initialized on first use. // and destructed when other static storage duration objects are destroyed. static P p_s_item(T::id(), T::desc()); return p_s_item; // Note its not guaranteed to be created before main(). // But it is guaranteed to be created before first use. } </code></pre> <p>So here you get the benefits of a global (whatever they are). You get guaranteed construction/destruction and you know the object will be correctly constructed before it can be used.</p> <p>The only change you need to make is:</p> <pre><code>void bar(int cnt) { for (int i = 0; i &lt; cnt; ++i) { PP(2, "description", pp); pp.p_s().doStuff(); // ^^ Add the braces here. } } </code></pre>
    singulars
    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