且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

关于fstream缓冲区,flush()和sync()之间有什么区别?

更新时间:2022-06-08 05:33:17

basic_ostream :: flush
这是一个 non-virtual 函数,将未提交的更改写入基础缓冲区。如果发生错误,它将在使用的流对象中设置一个错误标志。这是因为返回值是对流本身的引用,以允许链接。

basic_ostream::flush This is a non-virtual function which writes uncommited changes to the underlying buffer. In case of error, it sets an error flag in the used stream object. This is because the return value is a reference to the stream itself, to allow chaining.

basic_filebuf :: sync
这是 virtual 函数,该函数将所有未完成的更改写入基础文件,并返回错误代码以表示成功或失败。

basic_filebuf::sync This is a virtual function which writes all pending changes to the underlying file and returns an error code to signal success or failure.

endl
当将其应用于 ostream 时,将写入'\n'到流中,然后在该流上调用 flush

endl This, when applied to an ostream, writes an '\n' to the stream and then calls flush on that stream.

因此,本质上是: flush 是任何流的更通用的功能,而 sync 明确绑定到文件。 flush 是非虚拟的,而 sync 是虚拟的。在继承的情况下,这改变了如何通过指针(指向基类)使用它们。此外,它们在报告错误的方式上也有所不同。

So, essentially: flush is a more general function for any stream, whereas sync is explicitly bound to a file. flush is non-virtual, whereas sync is virtual. This changes how they can be used via pointers (to base class) in the case of inheritance. Furthermore, they differ in how they report errors.