这段代码有什么问题以及如何解决?
int _tmain(int argc, _TCHAR* argv[])
{
std::ostream * o = &std::cout;
char text[4096];
char *file = "D://test.txt";
if ( file != NULL )
{
strcpy ( text, file );
strcat ( text, ".log" );
o = & std::ofstream ( text );
}
*o << "test"; //Exception
return 0;
}
最佳答案
o = & std::ofstream ( text );
右边的表达式创建了一个临时对象,你得到了在表达式末尾销毁的临时对象的地址。之后使用 o
会调用未定义的行为。
你应该这样做:
{
//...
o = new std::ofstream ( text );
if ( *o )
throw std::exception("couldn't open the file");
}
//...
if ( o != &std::cout )
delete o; //must do this!
关于C++,std::ofstream,异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6959533/