CKTIS / C++
std::basic_ostream::flush — synchronize the output buffer
std::basic_ostream::flush requests synchronization of a stream buffer and returns a reference to the same stream. It does not append a newline; synchronization failure is reported through badbit.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
basic_ostream& flush();
// Usage:
os.flush();std::basic_ostream::flush is an unformatted output function, called as os.flush(). It returns *this, allowing operations to be chained. It does not itself append characters.
If rdbuf() is not a null pointer, it constructs a sentry object. When that object permits the operation, it calls rdbuf()->pubsync(). A result of -1 triggers setstate(badbit), which may throw std::ios_base::failure depending on the exception mask. If sentry does not permit the operation, synchronization is skipped.
os << std::flush calls the same member function. std::endl additionally inserts a newline before calling it. Synchronization depends on the buffer type: it should not be equated with a guarantee of durable storage on physical media.
The example uses a custom buffer whose sync() counts calls and reports success. Even without stored characters, out.flush() invokes synchronization; the expected output is 1 followed by a newline.
Examples
#include <iostream>
#include <ostream>
#include <streambuf>
class CountingBuffer : public std::streambuf {
public:
int sync_calls = 0;
protected:
int sync() override {
++sync_calls;
return 0;
}
};
int main() {
CountingBuffer buffer;
std::ostream out(&buffer);
out.flush();
std::cout << buffer.sync_calls << '\n';
}
Result
1
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.