Home > Net >  Why do compilers now accept to call str() member on a returned std::ostream& from std::stringstream:
Why do compilers now accept to call str() member on a returned std::ostream& from std::stringstream:

Time:09-19

Consider the following line:

std::string s = (std::stringstream() << "foo").str();

This should not compile because std::stringstream::operator<<() is inherited by std::ostream and returns a std::ostream& which does not have an str() member.

It seems the main compilers are now accepting this code where they didn't in the past. I would like to understand what standard change happened to make this to compile ?

I made some tests with gcc, clang and msvc and I could find the version where the change happened:

Compiler Rejects until (version) Accepts from (version)
GCC 11.1 11.2
Clang 12.0.1 13.0.0
MSVC v19.14 v19.15

You can find the test here

CodePudding user response:

They all added the rvalue overload (see here) very late.

The rvalue overload was introduced in C 11 and returns the same type of stream as its left-hand operand.

  • Related