问题
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?
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/59473325/no-member-named-str-in-stdbasic-ostreamchar-with-gcc-and-clang-but-no-p