c++ - 将 ostream 作为引用传递时出现段错误

标签 c++

我正在编写一个代码,其中输出要么是标准输出,要么是一个文件。为此,我发现使用 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;
}

代码编译正常,但在运行时出现段错误。 Valgrind 说 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;
}

关于c++ - 将 ostream 作为引用传递时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46927230/

相关文章:

c++ - 为什么 const char* 强制转换为 std::string 有效?

c++ - 如何计算(A*B)%C?

c++ - 删除从析构函数调用的抛出析构函数

C++游戏训练器进程监控

c++ - 获取连接到图中节点的最大边数

C++ 获取分配节的基地址

c++ - 具有结构数据类型的链表

c++ - 告诉子类对父类(super class)的 protected 变量做某事是一种好习惯(也许是一些已知的设计模式?)?

c++ - OpenGL 在纹理相交处失败

c++ - 是否可以更改从 GetTickCount() 返回的刻度计数值?