将 ostream 作为引用传递时出现错误

Segfault while passing ostream as reference

本文关键字:错误 ostream 引用      更新时间:2023-10-16

我正在编写一个代码,其中输出要么是标准输出,要么是文件。 为此,我发现使用ostream很方便。 看来我没有适当地使用它。 下面是一个最小示例:

#include <fstream>
struct A {
  std::ostream *os;
  A (const char *fn) {
    std::filebuf fb;
    fb.open (fn, std::ios::out);
    os = new std::ostream(&fb);
  }
  std::ostream &getOS () {
    return *os;
  }
};
int main(int argc, char **argv) {
  A a("foo.txt");
  a.getOS() << "bar" << std::endl;
  return 0;
}

代码编译正常,但我在运行时遇到分段错误。 瓦尔格林德说Use of uninitialised value of size 8,但我不能正确解释。 同样,gdb 给出了违规行(调用 a.getOS() ),但我不知道如何纠正它。

正如@Jodocus所评论的,变量 std::filebuf fb 在构造函数中是本地的。当它超出范围时,它将被销毁。这个问题可以通过定义 std::filebuf fb 作为成员变量来纠正。

#include <fstream>
struct A 
{
    std::ostream *os;
    std::filebuf fb;
    A (const char *fn) 
    {       
        fb.open (fn, std::ios::out);
        os = new std::ostream(&fb);
    }
    std::ostream &getOS () 
    {
        return *os;
    }
};
int main(int argc, char **argv) 
{
    A a("/home/test.txt");
    a.getOS() << "bar" << std::endl;
    return 0;
}
相关文章: