在静态对象的析构函数中使用cout [英] Using cout in destructors of static objects
问题描述
给出我的代码的精简版本:
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;
}
程序打印结尾.
但是,作为较大程序的一部分,它在尝试写入 ostream
时会SEGFAULTS.
The program prints The end.
However, as part of a larger program, it SEGFAULTS while attempting to write to the ostream
.
我正在尝试确保在程序终止时总是打印一些文本.我正在尝试使用iostream合法吗?使用 atexit(3)
会更好吗?
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)
?
我认为,因为 cout
是在我使用它之前构造的,所以它会在之后被销毁;因此尚不清楚为什么上面的代码不总是有效.
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.
如果我将第7行更改为直接写入 cout
而不是通过引用,则可以正常工作.那就更奇怪了.
If I change line 7 to write to cout
directly rather than via the reference, it works fine. That's even more bizarre.
推荐答案
如果在构造静态对象后调用 atexit()
,则在调用该对象后,静态对象将被销毁.因此,可以使用 atexit()
解决该问题.
If you call atexit()
after the construction of the static object then the static object will be destroyed after the call to that object. So yes using atexit()
should resolve the problem.
这篇关于在静态对象的析构函数中使用cout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!