title: Using cout in destructors of static objects
body: <p>Given this whittled down version of my code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  struct S {
    S( ostream &amp;os ) : os_( os ) { }
    ~S() { os_ &lt;&lt; "The end.\n"; }         // line 7
    ostream &amp;os_;
  };
  
  void f() {
    static S s( cout );
    (void)s;
  }
  
  int main() {
    f();
    return 0;
  }
  </code></pre>
  
  <p>The program prints <code>The end.</code> However, as part of a larger program, it SEGFAULTS while attempting to write to the <code>ostream</code>.</p>
  
  <p>I'm trying to ensure that some text will <em>always</em> get printed at program termination. Is what I'm trying to do legal using iostreams?  Would it be better to use <code>atexit(3)</code>?</p>
  
  <p>I thought that because <code>cout</code> was constructed before my using it, that it would be destroyed after; so it's not clear why code like the above should't always work.</p>
  
  <h2>Update</h2>
  
  <p>If I change line 7 to write to <code>cout</code> directly rather than via the reference, it works fine. That's even more bizarre.</p>