提问人:ivanovIAVD 提问时间:11/12/2020 最后编辑:YksisarvinenivanovIAVD 更新时间:11/12/2020 访问量:97
将 std::ofstream 重定向到 std::cout 时失败
Fail while redirect a std::ofstream to std::cout
问:
我想将 std 重定向到一个文件。
为此,我编写了一个 ,其中我连接/断开 .class Foo
writeToFilEnabled
但是,存在分段错误。这是怎么回事?
#include <iostream>
#include <fstream>
class Foo {
public:
Foo() {
out.open("out.txt");
coutbuf = std::cout.rdbuf();
}
void writeToFileEnabled(bool enabled) {
if (enabled)
std::cout.rdbuf(out.rdbuf());
else
std::cout.rdbuf(coutbuf);
}
void test(int a) {
std::cout << a << "\n";
}
private:
std::ofstream out;
std::streambuf * coutbuf;
};
int main()
{
Foo foo;
foo.test(1);
foo.test(2);
foo.writeToFileEnabled(true);
foo.test(3);
foo.test(4);
}
答:
0赞
user11498001
11/12/2020
#1
你的 foo 对象是 main 函数中的局部变量,所以当 main 返回时,foo 被销毁,cout 持有指向你现在被销毁的 ofstream 的指针。当程序退出时,退出处理程序会尝试破坏 cout,这会导致它访问无效的 Foo::out 对象并使程序崩溃。您可以尝试将 foo 放在全局范围内,或者在 main 函数的末尾调用 foo.writeToFileEnabled(false)。
评论
1赞
ivanovIAVD
11/12/2020
好的,也许在析构函数调用中?std::cout.rdbuf(coutbuf)
评论
out.is_open()
true
std::cout
stdout
std::cin.tie(nullptr)
stdout
freopen