问题描述
我想将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);
}
解决方法
您的foo对象是main函数中的局部变量,因此当main返回时,foo被销毁,而cout拥有指向您现在已销毁的流的指针。当程序退出时,退出处理程序将尝试破坏cout,这将导致cout访问无效的Foo :: out对象并使程序崩溃。您可以尝试将foo放在全局范围内,或在主函数的末尾调用foo.writeToFileEnabled(false)。