Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

no member named 'str' in 'std::basic_ostream<char>' with gcc and clang, but no problem with msvc

Tags:

c++

std

gcc

clang

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?

like image 763
Paul Jurczak Avatar asked Dec 24 '19 20:12

Paul Jurczak


2 Answers

there is clearly str() member of ostringstream

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.

like image 80
HolyBlackCat Avatar answered Nov 08 '22 12:11

HolyBlackCat


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

like image 26
Вячеслав Avatar answered Nov 08 '22 11:11

Вячеслав