Given this whittled down version of my code:
#include <iostream>
using namespace std;
struct S {
  S( ostream &os ) : os_( os ) { }
  ~S() { os_ << "The end.\n"; }         // line 7
  ostream &os_;
};
void f() {
  static S s( cout );
  (void)s;
}
int main() {
  f();
  return 0;
}
The program prints The end. However, as part of a larger program, it SEGFAULTS while attempting to write to the ostream.
I'm trying to ensure that some text will always get printed at program termination. Is what I'm trying to do legal using iostreams?  Would it be better to use atexit(3)?
I thought that because cout 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.
Update
If I change line 7 to write to cout directly rather than via the reference, it works fine. That's even more bizarre.
 
     
    