Given this shortened version of my code:
#include <iostream>
using namespace std;
struct S {
S( ostream &os ) : os_( os ) { }
~S() { os_ << "The end.\n"; }
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 when trying to write to ostream.
I am trying to ensure that some text is always printed when the program ends. Am I trying to make legal use of iostreams? Would it be better to use atexit(3)?
I thought that since it coutwas built before my use, it will be destroyed after; therefore, it is not clear why code like the one above should always work.
Update
If I change line 7 to write directly to cout, and not through a link, it works fine. This is even weirder.