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