繁体   English   中英

将 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);
}

你的 foo 对象是 main 函数中的一个局部变量,所以当 main 返回时, foo 被销毁并且 cout 持有一个指向你现在被销毁的 ofstream 的指针。 当程序退出时,退出处理程序试图破坏 cout,这导致它访问无效的 Foo::out 对象并使程序崩溃。 您可以尝试将 foo 放在全局范围内或在 main 函数的末尾调用 foo.writeToFileEnabled(false) 。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM