gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:06:04 25 4
gpt4 key购买 nike

根据 C++ 标准,您不能将临时变量绑定(bind)到非常量引用。由于流输出操作符定义为

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++ 的明确答案吗?

最佳答案

有一个通过右值引用获取流的重载:

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

temp 作为 os 传递。来自 reference .

关于c++ - 为什么我可以在临时 std::ofstream 对象上使用 `operator<<`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57867724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com