簡體   English   中英

為什么我可以在臨時std :: ofstream對象上使用`operator <<`?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM