According to the C++ standard you cannot bind a temporary to a non-const reference. Since the stream output operator is defined as
template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os,
const std::basic_string<CharT, Traits, Allocator>& str);
I would expect it to not be callable on temporary stream objects. However, I tried the following and got unexpected results
#include <fstream>
std::ostream& print(std::ostream &stream) {
stream << "test\n";
return stream;
}
int main() {
std::fstream("") << "test\n";
// print(std::fstream("")); // Doesn't compile, as expected
}
This compiles on GCC trunk, Clang trunk and MSVC 19. I even tried -pedantic-errors
on the first two. While technically possible that all three are wrong, it is likely that I am misunderstanding something.
Can somebody find a definitive answer in the standard on whether this is legal C++ or not?