将 ostream 作为引用传递时出现错误
Segfault while passing ostream as reference
我正在编写一个代码,其中输出要么是标准输出,要么是文件。 为此,我发现使用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;
}
相关文章:
- 在抛出 'std::runtime_error' 的实例后终止调用 what(): Filebuf 和 ostream 的 I/O 错误
- boost::interprocess::file_lock 与 std::ostream 一起使用时的错误行为
- 从 std::ostream 重载 << 运算符时,为什么编译器会给出"too many parameters for this operator function"错误?
- 运算符的歧义错误<<自定义 std::ostream 子类中的重载
- 打印矩阵后分割错误,但在打印额外行后修复(ostream <<操作器)
- ostream 运算符<<错误C++
- 尝试重载时'ostream'和'istream'错误C++
- C++,错误:" no operator "== " matches these operands ",ostream/istream
- 为什么在重载的 ostream 运算符中引用 lambda 中的向量会导致错误
- C++以友元身份重载 ostream 运算符会导致错误:变量在此上下文中是私有的
- 当我编译引用 std::ostream 时,我有一个奇怪的错误弹出
- 将 ostream 作为引用传递时出现错误
- 错误:无法将"std::ostream {aka std::basic_ostream<char>}"lvalue 绑定到"std::basic_ostream&<char>&
- high_resolution_clock错误:无法将"std::ostream {aka std::basic_ostream}"<char>lvalue 绑定到"std::basic_
- 错误:非静态引用成员"std::ostream&Student::out",无法使用默认赋值运算符
- C++ istream >> 和 ostream << 错误
- 错误:无法在实现文件中绑定“std::ostream”
- 错误:“oStream”未命名类型
- oStream&没有命名类型错误。我在这里做错了什么?
- C++编译器错误,涉及从类型为"std::ostream"的临时引用初始化类型为"std::ostream"的非常量引用