在使用g++退出后,我会得到以下程序的一个分段错误:
#include <iostream>
#include <fstream>
int
main()
{
std::ofstream logfile( "logfile" ) ;
if( !logfile.is_open() )
{
std::cerr << "oops ofstream\n" ;
return -1 ;
}
std::clog.flush() ;
std::clog.rdbuf( logfile.rdbuf() ) ;
std::clog << "test output\n" ;
std::clog.flush() ;
std::cerr << "all done\n" ;
return 0 ;
} 有什么线索吗?
发布于 2016-02-24 19:48:03
std::clog和好友的生存期由std::ios_base::Init类型的静态对象(C++11 27.5.3.1.6类ios_base::Init)管理。当该对象被销毁时(在main()返回之后),它执行以下正在销毁std::clog和相关iostream对象的操作(C++11 27.5.3.1.6/4类ios_base::Init):
调用cout.flush()、cerr.flush()、clog.flush()、wcout.flush()、wcerr.flush()、wclog.flush()
对flush()的调用将在clog中使用rdbuf()对象,而且由于先前传递给clog的logfile.rdbuf()已被销毁,您将得到未定义的行为。
https://stackoverflow.com/questions/35611069
复制相似问题