如果调用 ostream operator<< 则未指定可能会失败或抛出任何异常,我从未遇到过这种情况。
struct MyClass {
int data;
// I/O operators with noexcept specifier
friend std::istream& operator>>(std::istream &in, MyClass &obj) noexcept;
friend std::ostream& operator<<(std::ostream &out, const MyClass &obj) noexcept;
};
最佳答案
原因没有operator >>
和 operator <<
标记为 noexcept
是因为 std::basic_ios::exceptions
.此成员函数存在于从 std::basic_ios
继承的所有对象中。并允许您配置流以针对某些故障模式抛出异常。如果运算符是 noexcept
那么您不能将它们与设置了异常的流一起使用。
关于iostream 运算符重载的 C++ 异常规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58752411/