C++ 标准是否保证当 'rdbuf' 的 return 值传递给流输出运算符时,缓冲区的内容被打印出来

Does the C++ standard guarantee that when the return value of 'rdbuf' passed to the stream output operator, he conent of the buffer gets printed out

考虑以下代码片段:

std::stringstream ss;
ss << "hello world!\n";
auto a = ss.rdbuf();
std::cout << a; // prints out "hello world!

变量a 是指向std::stringbuf 类型对象的指针。当它传递给流输出操作符 << 时,使用 GCC9.4,打印出 a 指向的流缓冲区的内容。

我的问题是:这种行为只是 std::stringbuf 在 GCC 中实现的方式的意外,还是语言标准保证这将始终有效?

A std::basic_stringbuf 派生自 std::basic_streambuf。 cppreference 介绍其用途:

The I/O stream objects std::basic_istream and std::basic_ostream, as well as all objects derived from them (std::ofstream, std::stringstream, etc), are implemented entirely in terms of std::basic_streambuf.

这是什么意思?好吧,让我们看一下 std::basic_istream::operator<< here:

的重载集

basic_ostream& operator<<( std::basic_streambuf<CharT, Traits>* sb ); (10)

Behaves as an UnformattedOutputFunction. After constructing and checking the sentry object, checks if sb is a null pointer. If it is, executes setstate(badbit) and exits. Otherwise, extracts characters from the input sequence controlled by sb and inserts them into *this until one of the following conditions are met:

  • end-of-file occurs on the input sequence;
  • inserting in the output sequence fails (in which case the character to be inserted is not extracted);
  • an exception occurs (in which case the exception is caught).

If no characters were inserted, executes setstate(failbit). If an exception was thrown while extracting, sets failbit and, if failbit is set in exceptions(), rethrows the exception.

所以,是的,标准保证 std::cout << ss.rdbuf(); 会产生您观察到的效果。