This code snippet (https://gcc.godbolt.org/z/hKDMxm):
#include <iostream>
#include <sstream>
using namespace std;
int main() {
auto s = (ostringstream{} << "string").str();
cout << s;
return 0;
}
compiles and runs as expected with msvc, but fails to compile with clang 9.0.0 and gcc 9.2 giving this error message:no member named 'str' in 'std::basic_ostream<char>'. Looking at https://en.cppreference.com/w/cpp/io/basic_ostringstream/str there is clearly str() member of ostringstream. Why clang and gcc are failing to compile this code?
there is clearly
str()member ofostringstream
Yes, but according to cppreference this overload of << should return a reference to basic_ostream<...> rather than ostringstream.
libstdc++ (GCC's standard library) does exactly this, while libc++ (Clang's standard library) and MSVC's standard library behave incorrectly here, technically.
However, it seems there is an open defect report suggesting that the overload of << that works with rvalue streams should return the exact stream type that was passed to it. If it gets accepted, your code will be valid.
operator<< is member of std::ostream, and returns std::ostream& as described here
MSVC obviously has own overload this operator for std::ostringstream, what is not in standard
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With