[英]Why can I use `operator<<` on temporary std::ofstream objects?
根据C ++标准,您不能将临时绑定到非const引用。 由于流输出运算符定义为
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 << "test\n";
return stream;
}
int main() {
std::fstream("") << "test\n";
// 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 );
temp以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
。
请注意,提取( >>
)也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.