+ Reply to Thread
Results 1 to 2 of 2

Thread: What is set_new_handler in C++?

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    29

    What is set_new_handler in C++?

    Hi All,

    What is set_new_handler in C++?

    How to use it?

    Regards.

  2. #2
    Hi,

    set_new_handler executes when 'new' operator fails to allocate specified memory.

    example:

    Code:
    #include<new>
    #include<iostream>
    
    void MyNewHandler()
    {
    	//a. Try de-allocating some of the memory if you have access to do so.
    	//b. If more space is available then return
    	//c. If no more space is available then
    		//1. throw bad_alloc exception
    		//2. Exit the program.
    	std::cout << "Failed to allocate required memory!" ;
    	throw std::bad_alloc() ;
    }
    
    void UseOfSetNewHandler()
    {
    	std::set_new_handler(MyNewHandler) ;
    
    	try
    	{
    		while(true)
    		{
    			unsigned char *pGarbage = new unsigned char[100000000L] ;
    			std::cout << "Alocated 1000000 bytes" << std::endl ;
    		}
    	}
    	catch (std::exception exp)
    	{
    		std::cout << exp.what() << std::endl ;
    	}
    }
    Note:
    Please note that set_new_handler returns new_handler if there is already new_handler installed using set_new_handler.

    Regards.

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts