You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ios(含ifstream)对象的exception mask重置为默认值?C++标准是否定义?

Resetting an ios Object's Exception Mask to Default

Great question! Let's break this down into clear, actionable parts—covering the standard's rules and reliable reset methods that don't depend on pre-stored state.

Is the default exception mask defined by the C++ standard?

Yes, absolutely. The C++ standard explicitly states that when an ios_base (the base class for all stream objects like ios, ifstream, ostream, etc.) is initialized, its exception mask defaults to std::ios_base::goodbit. This means no exceptions are thrown by default for any stream state changes—you have to explicitly enable exceptions for specific error bits (like failbit or badbit) using the exceptions() method.

How to reset the exception mask to default?

You don't need to rely on pre-storing the original mask state (which, as you noted, isn't always feasible if you don't control the stream's initialization). There are two straightforward, standard-compliant ways:

  • Directly set to goodbit: Since the standard guarantees this as the default value, you can reset the mask with a direct assignment:
    // Works for any ios-derived object (ifstream, ostream, etc.)
    your_stream.exceptions(std::ios_base::goodbit);
    
  • Use a temporary ios_base object: For extra robustness (in case of any hypothetical standard updates, though this is highly unlikely), you can create a fresh, default-constructed ios_base instance and copy its exception mask:
    your_stream.exceptions(std::ios_base{}.exceptions());
    

Why the pre-stored state alternative falls short

As you pointed out, storing the original mask only works if you can capture it before any modifications are made. This breaks down if you're dealing with streams created by third-party code, or if you don't have control over when the mask is first altered. The methods above avoid this entirely by leaning on the standard's guaranteed default value.

Here's a quick example putting this into practice:

#include <fstream>
#include <iostream>

int main() {
    std::ifstream input("example.txt");
    
    // Modify the mask to throw on fail/bad bits
    input.exceptions(std::ios_base::failbit | std::ios_base::badbit);
    
    // Reset back to default (no exceptions triggered)
    input.exceptions(std::ios_base::goodbit);
    
    // Or use the temporary object approach
    // input.exceptions(std::ios_base{}.exceptions());
    
    return 0;
}

内容的提问来源于stack exchange,提问作者sancho.s ReinstateMonicaCellio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:06:21