C ++应用程序在实例化一个ofstream对象时崩溃。

时间:2010-11-18 12:12:09

标签: c++ ofstream interix pgi

运行C ++应用程序时,我遇到了一个非常棘手的问题。我在Windows Xp的Interix子系统上使用pgcpp编译器。我的问题基本上在这里描述:

我在头文件中有一个类定义。此头文件包含在一个源文件中。该类有两个构造函数,基本上用于实现记录器。第一个构造函数将ostream * out作为参数,而第二个重载构造函数接受文件名和默认布尔值false。第二个构造函数的目的是获取我们传递的文件名的流,并开始将消息记录到它。构造函数中的代码如下:

MessageLogger::MessageLogger(std::ostream *out): p_out (out), p_ofstream (0)  
{  
    if (p_out)  
    {  
        (*p_out) << "Started logging messages" << endl;  
    }  
}  

MessageLogger::MessageLogger (char const *filename, bool append_to_file) : p_out (0),   p_ofstream (0)  
{  
    if (append_to_file)  
    {  
    p_ofstream = new std::ofstream (filename, ios::app);  
    }  
    else  
    {  
        p_ofstream = new std::ofstream (filename);  
    }  

    p_out = p_ofstream;  

    if (p_out)  
    {  
        (*p_out) << "Started logging messages" << endl;  
    }  
}  

p_out和p_ofstream的声明如下:

std::ostream *p_out;
std::ofstream *p_ofstream;
unsigned int p_indent_level;

上述三个都是私人会员。 MessageLogger类的实例化完成如下:

MessageLogger logger ("filename");

请注意,append_to_file的默认值为false。 PGDBG也行为不端。当控件位于p_ofstream = new std::ofstream (filename);并且它进入随机位置然后应用程序崩溃时,我莫名其妙地能够介入。

此外,当我尝试在PGDBG中看到混合或反汇编代码时,调试器崩溃并显示以下消息:

jpgdbg parse: Newline must follow cmd in 'eleq "0" struct MessageLogger *Mes
sageLogger::MessageLogger(struct basic_ostream *out); (TranslatorGeneric.cpp
)
'
jpgdbg jpgdbgFileSelector processMsg: Warning unexpected msg token 5
jpgdbg parse: Newline must follow cmd in 'eleq "1" struct MessageLogger *Mes
sageLogger::MessageLogger(char *filename, unsigned char append_to_file); (Tr
anslatorGeneric.cpp)
'
jpgdbg jpgdbgFileSelector processMsg: Warning unexpected msg token 5

我无法在示例程序中重现这一点,我完成了与上面相同的操作,但一切正常。有人可以解释一下发生了什么,以及是否有解决方法?

谢谢, 阿迪亚。

1 个答案:

答案 0 :(得分:-1)

为什么使用动态分配的ofstream实例?你为什么不做以下的事......

class Logger
{
  public:
    Logger(ostream& str) : _str(str.rdbuf()) // use the buffer from the stream
    {
      _str << "writing to passed in buffer" << endl;
    }
    Logger(const char* fname, bool append = false) : _str(cout.rdbuf())
    {
      _file.open(fname, (append)? ios::out|ios::app : ios::out);
      if (_file.is_open())
        _str.rdbuf(&_file); // redirects to file, else remains on cout

      _str << "expected to be logging to: " << fname << endl;
    }

    // use as needed

  private:
    filebuf _file;
    ostream _str;
};

这样即使您的文件失败,您仍然会将日志输出转到cout ...

回到你的问题,HW_NEW做了什么?用你提供的基本信息真的很难说......