Note that there are some explanatory texts on larger screens.

plurals
  1. POGlobal objects constructors called after first use of object
    primarykey
    data
    text
    <p>As far as I know the constructors of global objects need to be called before anybody tries using those objects. However in my program this doesn't seem to be the case. Here is my simplified code (I compile it with gcc version 4.6.3-1ubuntu5)</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; using namespace std; struct type_data { int id; type_data() : id(-1) // set some invalid id { cout &lt;&lt; "creating a new type data" &lt;&lt; endl; } }; template &lt;typename T&gt; struct type_data_for_type { static type_data data; }; template &lt;typename T&gt; type_data type_data_for_type&lt;T&gt;::data; struct type_registry { static type_registry&amp; instance() { static type_registry i; return i; } void register_type(type_data&amp; t) { cout &lt;&lt; "registering a type" &lt;&lt; endl; t.id = last_id++; } int last_id; }; template &lt;typename T&gt; struct registrator { registrator() { type_registry::instance(). register_type(type_data_for_type&lt;T&gt;::data); } int unused; static registrator payload; }; template &lt;typename T&gt; registrator&lt;T&gt; registrator&lt;T&gt;::payload; class foo {}; inline void register_foo() { registrator&lt;foo&gt;::payload.unused = 1; } int main() { cout &lt;&lt; type_registry::instance().last_id &lt;&lt; endl; cout &lt;&lt; type_data_for_type&lt;foo&gt;::data.id &lt;&lt; endl; return 0; } </code></pre> <p>Basically it registers the type foo globally via register_foo. I expect the output to be:</p> <pre><code>creating a new type data registering a type 1 0 </code></pre> <p>But instead it is:</p> <pre><code>registering a type creating a new type data 1 -1 </code></pre> <p>This means that i've set the id of a <code>type_data</code> object before its constructor was called. </p> <p>So, is this a compiler bug? Am I missing something? Can I make this work?</p>
    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. 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