[英]Destructors/Static variables. Can't delete objects with explicit destructors and static counting variables is negative
[英]Using cout in destructors of static objects
鉴于我的代码的这个缩小版本:
#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 end.
但是,作为更大程序的一部分,它在尝试写入ostream
会出现SEGFAULTS。
我正在努力确保在程序终止时始终打印一些文本。 我正在尝试使用iostream合法吗? 使用atexit(3)
会更好吗?
我认为因为cout
是在我使用之前构建的,所以它会在之后被破坏; 所以不清楚为什么像上面这样的代码不应该总是有效。
如果我改变第7行直接写入cout
而不是通过引用,它可以正常工作。 那更奇怪了。
如果在构造静态对象后调用atexit()
,则在调用该对象后将破坏静态对象。 所以是的,使用atexit()
应该可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.