美文网首页
C++文章学习笔记

C++文章学习笔记

作者: 沉思故事 | 来源:发表于2018-05-23 15:17 被阅读17次

    用T:作标题前缀,方便搜索

    T: Who calls std::terminate?

    异常机制相比于返回值errno的优势之一在于后者如果忘记调用,就不知道出错,但异常不会;

    异常可能会导致局部变量析构不能完成【在main之前如果runtime没有catch到异常,也许stack unwinding不会发生,m也不会析构了,这一点我测试过】,如以下代码:

    struct M {
     ~M() {}
    };
    
    main() {
     M m;
     throw SomeException();
    }
    

    对于全局变量初使化,我们没有办法加exception handler的,所以有以下规则:

    • 尽量不要用全局变量。它导致许多问题,引用透明性问题,单元测试变得麻烦,初使化失败的问题,构造顺序问题
    • 尽可能使用buildin type的初使化,它们不会失败
    • 尽可能使用编译时初使化,用constexpr强制
    • 如果有non-trivial运行时的开销,考虑在main顶层初使化或使用单例或者函数局部对象,这样也可以捕获其可能产生的异常

    像以下代码:

    catch(MyException exc) {
       //
    }
    

    MyException对象是按值传递,那么就可能其copy ctor发生第二次异常(比如string拷贝就可能异常),导致直接terminate.所以尽可能用常量左值引用。以下代码是我的验证:

    class my_exception : public exception {
    public:
        ~my_exception() {
    
        }
    
        my_exception() {}
        my_exception(const my_exception& o) {
            throw string("my_exception");
        }
    };
    
    int main(int argc, char *argv[])
    {
        M m;
    
        try {
            throw my_exception();
        } catch(my_exception e) {  //
            cout << "caught\n";
        }
        return 0;
    }
    

    如果按上面运行,则

    This application has requested the Runtime to terminate it in an unusual way.
    Please contact the application's support team for more information.
    terminate called after throwing an instance of 'std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >'
    

    将e修改为const my_exception&后,正常打印caught和very important msg

    被noexcept声明的函数意味着只要throw就调terminate【难道不加它就不调terminate ???】,编译器或runtime可以不做unwind stack的工作,或者部分unwind

    rethrow_nested是表示low-level exception被high-level exception所包住,这样在high-level handler里就可以inspect那个low-level exception
    rethrow_exception常常用于一个线程中throw了exception,在另一个线程中去check它

    thread析构时,它不是joinable,就会terminate; 推荐使用std::async
    abort不会调terminate handler ? YES ! terminate默认会调abort

    T: Using std::terminate 更加详细的介绍terminate机制

    怎么理解error ?
    可以分为可恢复与不可恢复。可恢复的错误可能稍微处理下或丢弃就可以继续运行,不可恢复的可能有Bug,有时需强制停止

    stack unwinding是用来处理可恢复性error的,一些动作被丢弃,只执行相关的clean-up,希望它能从error中恢复并继续正常运行;
    terminate是用来处理不可恢复的error,它的行为与platform有关
    std::_Exitstd::exit不一样,后者会干各种清理工作,如静态结构的析构、atexit注册函数的调用,但前者不会,不过是否flush file取决于实现

    在terminate handler里重新调用原程序,似乎是可以,但有点Insane,会导致栈溢出;
    如果程序占用了全部资源(不是独占的资源),它突然停止会导致资源hung住,为确保其它程序能用,必须安全释放;
    用log记录terminate事件是可以的,但注意log对象往往是global,global对象对于terminate经常是不可靠的(除了cin,cout,因为它们不会被销毁

    Logger * logger = new Logger;
    [[noreturn]] void onTerminate() noexcept {
        try {
            if (logger) {
                logger->logAbnormalTermination();
            }
        } catch(...) {
            //ignore !
        }
        std::_Exit(EXIT_FAILURE);
    }
    
    int main() {
        std::set_terminate(&onTerminate);
        //run ...
    }
    

    如上代码犯了两个规范:

    1. 它不该吞了异常
    2. logger没有释放。但这关系不太(在评论里,他说:不是所有leak都是危险的,虽然它会被static analyzer检测到,但我们不需要修复所有leak),程序shutdown时都会被释放,它可保证在onTerminate里仍能工作(如果其它编译单元的global对象要在析构中用这个logger,当然是希望这个logger没被析构仍可用)
    3. 评论中Todd Greer有句话我觉得有意思:

    Just put some loud comments in place describing what you’re doing to keep it from being undone in maintainence
    为防止其它人不知道什么原因就把删除了,所以添加注释以说明

    1. 评论中Tony Van Eerd说可以使用placement new,看起来似乎不错
    [[noreturn]] void onTerminate() noexcept {
        if (auto exc = std::current_exception()) {
            try {
                rethrow_exception((exc));
            } catch (exception1 const& exc) {
                //additional action
            } catch (exception2 const& exc) {
                //...
            }
        }
    }
    

    如果在知道是什么异常导致了terminate,可以在terminate handler里用current_exception检查,如上述代码所示;
    比logging更好的方式是调一个系统函数使之core dump, run-time可以不做unwind stack的事,这样我们就可以在导致异常的那个点上生成core dump

    terminate handler不是线程安全的,需要加mutex;
    像这样在main之前安装handler,const auto installed { std::set_terminate(&handler));也不是最好的方式,因为其它全部全局变量可能在此之前throw

    有人说不要用terminate,因为它会终止程序,而我的程序无论何时都不能停止。事实上,terminate只会在错误无法恢复时才被调用,所以关键是要保证程序不能corrupt,超出了恢复范围。比如不要做non-trivial 全部初使化、不要在析构中写代码(这点??)、不要乐观地使用noexcept、不要使用thread(使用async ??);

    在实际情况下,停止某些程序会导致灾难性后果,那么就要:

    • 避免随机申请资源(资源申请是异常的主要来源)
    • 尽可能使用stack memory而不是Heap
    • 如果使用stl 存储少量元素,可以使用stack allocators
    • 异常适用于signaling资源申请失败,而不是输入验证这样的问题,它可以用optional解决【我怀疑这个说法 ??
    • c++无法给你百分百的保证程序不会terminate,如果想要100%,也许可以用函数式语言,它们至少在数学意义上是确定的

    T: Destructors that throw

    相关文章

      网友评论

          本文标题:C++文章学习笔记

          本文链接:https://www.haomeiwen.com/subject/sskrjftx.html