Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/memory/new/set new handler"

From cppreference.com
< cpp‎ | memory‎ | new
m (+seelaso, typo in title)
m (Text replace - "{{example cpp" to "{{example")
Line 35: Line 35:
  
 
===Example===
 
===Example===
{{example cpp
+
{{example
 
  |
 
  |
 
  | code=
 
  | code=

Revision as of 16:57, 19 April 2012

Template:cpp/memory/new/sidebar Template:ddcl list begin <tr class="t-dsc-header">

<td>
Defined in header <new>
</td>

<td></td> <td></td> </tr> <tr class="t-dcl ">

<td class="t-dcl-nopad">
std::new_handler set_new_handler(std::new_handler new_p)
</td>

<td class="t-dcl-nopad"> </td> <td class="t-dcl-nopad"> </td> </tr> Template:ddcl list end

Makes new_p the new global new-handler function and returns the previously installed new-handler.

Contents

Notes

The new-handler function is the function called by allocation functions whenever a memory allocation attempt fails. Its intended purpose is one of three things:

1) make more memory available

2) terminate the program (e.g. by calling Template:cpp)

3) throw exception of type Template:cpp or derived from Template:cpp

If new-handler returns, the allocation function repeats the previously-failed allocation attempt and calls the new-handler again if the allocation fails again. To end the loop, new-handler may call Template:cpp: if, after a failed allocation attempt, allocation function finds that Template:cpp returns a null pointer value, it will throw Template:cpp.

At program startup, new-handler is a null pointer.

Parameters

new_p - pointer to function of type Template:cpp, or null pointer

Return value

The previously-installed new handler, or a null pointer value if none was installed.

Exceptions

noexcept specification:  
noexcept
  

Example

#include <iostream>
#include <new>
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';
    }
}

Output:

Memory allocation failed, terminating
std::bad_alloc

See also

Template:cpp/memory/new/dcl list operator newTemplate:cpp/memory/new/dcl list set new handlerTemplate:cpp/memory/new/dcl list new handlerTemplate:cpp/memory/new/dcl list bad alloc