为什么我可以在临时 std::ofstream 对象上使用"operator<<"?



根据C++标准,您不能将临时引用绑定到非常量引用。由于流输出运算符定义为

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);

我希望它在临时流对象上不可调用。但是,我尝试了以下方法并得到了意想不到的结果

#include <fstream>
std::ostream& print(std::ostream &stream) {
stream << "testn";
return stream;
}
int main() {
std::fstream("") << "testn";
// print(std::fstream("")); // Doesn't compile, as expected
}

这在 GCC 主干、Clang 主干和 MSVC 19 上编译。我什至在前两个上尝试了-pedantic-errors。虽然从技术上讲,这三者都是错误的,但我很可能误解了什么。

有人能在标准中找到关于这是否合法C++的明确答案吗?

存在通过 Rvalue 引用获取流的重载:

template< class CharT, class Traits, class T >
basic_ostream< CharT, Traits >& operator<<( basic_ostream<CharT,Traits>&& os,
const T& value );

温度作为os传递。参考资料。

C++ 标准要求存在以下函数模板(C++17 n4659 30.7.5.5 [ostream.rvalue](:

template <class charT, class traits, class T>
basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>&& os, const T& x);

效果指定为os << x.

请注意,提取(>>(也存在同样的情况。

相关内容

最新更新