Consider the following code snippet:
std::stringstream ss;
ss << "hello world!\n";
auto a = ss.rdbuf();
std::cout << a; // prints out "hello world!
The variable a is a pointer to an object of the type std::stringbuf. When it is passed to the stream output operator <<, with GCC9.4, the content of the stream buffer pointed by a gets printed out.
My question is: is this behavior just an accident from the way std::stringbuf is implemented in GCC, or does the language standard guarantee this will always work?
A
std::basic_stringbufis derived from a std::basic_streambuf. Cppreference describes its use:What does that mean? Well, let's take a look at the overload set for
std::basic_istream::operator<<here:So, yes, it's guaranteed by the standard that
std::cout << ss.rdbuf();will have the effect you observed.