如果cout.rdbuf()用于切换缓冲区,从不设置回来,什么可能出错? [英] What can go wrong if cout.rdbuf() is used to switch buffer and never set it back?

查看:946
本文介绍了如果cout.rdbuf()用于切换缓冲区,从不设置回来,什么可能出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作者在标题下发布了此代码我的平台

The author presented this code under the title A bus error on my platform

#include <fstream>
#include <iostream>

int main()
{
    std::ofstream log("oops.log");
    std::cout.rdbuf(log.rdbuf());
    std::cout << "Oops!\n";
    return 0;
}

字符串Oops!\\\
打印到文件oops .log。该代码不恢复cout的streambuf,但VS2010没有报告运行时错误。

The string "Oops!\n" is printed to the file "oops.log". The code doesn't restore cout's streambuf, but VS2010 didn't report a runtime error.

推荐答案

> log 和 std :: cout 共享缓冲区,该缓冲区可能会被释放两次(一次 log 超出范围,然后在程序终止时再一次)。

Since log and std::cout share a buffer, that buffer will probably be freed twice (once when log goes out of scope, then once more when the program terminates).

这会导致未定义的行为,因此很难说明其原因会在他的计算机上触发总线错误,但会对您的计算机进行默认操作。

This results in undefined behavior, so it's hard to tell the exact reason why it triggers a bus error on his machine but silently fails on yours.

这篇关于如果cout.rdbuf()用于切换缓冲区,从不设置回来,什么可能出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆