简体   繁体   English

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

[英]Why can I use `operator<<` on temporary std::ofstream objects?

According to the C++ standard you cannot bind a temporary to a non-const reference. 根据C ++标准,您不能将临时绑定到非const引用。 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. 这编译在GCC主干,Clang主干和MSVC 19.我甚至在前两个尝试了-pedantic-errors 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? 有人可以在标准中找到关于这是否是合法C ++的确定答案吗?

There is overload which takes stream by Rvalue reference: 有一个重载,它通过Rvalue引用获取流:

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

temp is passed as os . temp以os传递。 From reference . 参考

The C++ standard mandates the following function template existing (C++17 n4659 30.7.5.5 [ostream.rvalue]): 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);

With effects specified as os << x . 使用指定为os << x

Note that the same exists for extraction ( >> ) as well. 请注意,提取( >> )也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM