what is the destruction order between global object and static variable?
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/6403055/object-destruction-in-c">Object destruction in C++</a>  </p>
</blockquote>



<p>Suppose we have two classes, one is called <code>Array</code> and the other one is called <code>MessageOnExit</code>.</p>

<p>Assume the <code>Array</code> class has a static data member called <code>counter</code>.</p>

<p>Here are the classes:</p>

<pre><code>class Array {
public:
    static int counter;
    Array(){counter++;}
    ~Array(){counter--;}
};

class MessageOnExit {
public:
    ~MessageOnExit(){cout &lt;&lt; Array::counter;}
};
</code></pre>

<p>The following is the <strong>"main"</strong> using these classes:</p>

<pre><code>// static variable definition
int Array::counter;
// global object definition
MessageOnExit message;

void main() {
    Array a1, a2;
    Array a3(a1);
}
</code></pre>

<p>The first two declarations will change <code>counter</code> to be 2 ensues two calls of the Empty/Default constructor 
The third declaration won't change the <code>counter</code> because the Default copy constructor will be called.</p>

<p>Now when the <code>main</code> execution is done, the value of the static member <code>counter</code>will be <code>-1</code> ensues the destructors calls (after a1, a2 and a3 are desroyed), and then the <code>message</code> destructor will be called, printing this value (<code>-1</code>).</p>

<p>My question is how do we know the static member <code>counter</code> is still alive and available when the <code>message</code> destructor is being called. </p>

<p>Also if I change the static/global object/variable definition order, that is, <code>message</code> is defined before <code>counter</code>, the value remains <code>-1</code>.</p>

<p>To summarize, no matter what changes I do, when the program terminates the message destructor success to access the static member <code>counter</code> and I don't understand why is that. As far as I understand if the global object <code>message</code> is defined first its destructor will be called last and therefore the <code>counter</code> value won't be available for its destructor.</p>

<p>Thanks in advance!
Guy</p>
