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

标签 c++ ofstream interix pgi

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

我在头文件中有一个类定义。该头文件包含在一个源文件中。这个类有两个构造函数,主要用于实现一个记录器。第一个构造函数采用 ostream *out 作为参数,而第二个重载构造函数采用文件名和默认 bool 值 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;

以上三个都是私有(private)成员。 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

我无法在示例程序中重现这一点,在示例程序中我做了与上面完全相同的事情,但一切正常。有人可以解释发生了什么,如果有解决办法吗?

谢谢, 阿迪亚。

最佳答案

为什么要使用动态分配的 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;
};

这样即使你的文件失败了,你仍然会有日志输出去计算...

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

关于C++ 应用程序在实例化 ofstream 对象时崩溃。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4214594/

相关文章:

c++ - 用 ofstream 写前导零

c++ - ofstream 不将缓冲区写入文件

c - stddef.h : error: duplicate 'unsigned'

c++ - 成对展开可变参数模板包

C++ ConvexHull of points 算法(及其索引)

c++ - 写很多txt文件(90),每个文件5MB,耗时1400s

C 编译器无法在 SUA/Interix 上创建可执行文件

c++ - 在 64 位机器上将 ponters 限制为 32 位

c++ - 手动设置空间引用时 LibLas 崩溃