C++,std::ofstream,异常

标签 c++ exception ofstream

这段代码有什么问题以及如何解决?

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/

相关文章:

c# - 从内存运行 exe 时出现 "Parameter count mismatch"

c++ - Ofstream 不写入文件 C++

c++ - 为什么对 isnan 的调用没有歧义? a.k.a. 使用引入 2 次相似函数声明的关键字

c++ - "lightweight type categorization idiom"的最简单实现?

c# - 除了 System.OutOfMemoryException 之外,string = string 还会抛出哪些异常?

c# - 尝试/捕捉性能

c++ - 如何加速我的 .bmp 类?

c++ - 将输出流对象和其他参数传递给多个线程

c++ - 使用 "for"打破 "break"循环被认为是有害的?

c++ - 对象上的范围解析运算符