【发布时间】:2016-09-30 11:11:32
【问题描述】:
为了更好地理解 C++ 中的缓冲流,我想编写一个简单的程序,其中 std::cout 缓冲区在终止前不会被刷新。因为我已经读到std::cout 在正常终止时被刷新,所以我尝试抛出一个运行时错误。我也避免使用std::endl,因为我知道这会强制刷新。第一次尝试:
//file noflush.cpp
#include <iostream>
int main() {
std::cout << "Don't write me to the console!";
throw 0;
}
用g++编译,从终端调用:
$ ./noflush
libc++abi.dylib: terminating with uncaught exception of type int
Don't write me to the console!Abort trap: 6
即使我强制出现运行时错误,缓冲区似乎仍会在终止时被刷新。是否可以将缓冲区中的一些数据“绞合”起来,不将其写入设备?
【问题讨论】:
-
只是说即使使用
std::abort()中止,缓冲区也会被刷新(使用 Apple LLVM 版本 6.0 (clang-600.0.57)(基于 LLVM 3.5svn)和 LLVM libc++),不过根据cppreference,它是实现定义的文件等开放资源是否关闭(在调用std::abort()时)。
标签: c++ stream buffer stdout cout