Can the C++ `new` operator ever throw an exception in real life?

前端 未结 18 1846
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 08:40

Can the new operator throw an exception in real life?

And if so, do I have any options for handling such an exception apart from killing my application?

18条回答
  •  爱一瞬间的悲伤
    2021-01-30 09:18

    The new-handler function is the function called by allocation functions whenever new attempt to allocate the memory fails. We can have our own logging or some special action, eg,g arranging for more memory etc. Its intended purpose is one of three things: 1) make more memory available 2) terminate the program (e.g. by calling std::terminate) 3) throw exception of type std::bad_alloc or derived from std::bad_alloc. The default implementation throws std::bad_alloc. The user can have his own new-handler, which may offer behavior different than the default one. THis should be use only when you really need. See the example for more clarification and default behaviour,

    #include 
    #include 
    
    void handler()
    {
        std::cout << "Memory allocation failed, terminating\n";
        std::set_new_handler(nullptr);
    }
    
    int main()
    {
        std::set_new_handler(handler);
        try {
            while (true) {
                new int[100000000ul];
            }
        } catch (const std::bad_alloc& e) {
            std::cout << e.what() << '\n';
        }
    }
    

提交回复
热议问题