`
izuoyan
  • 浏览: 8934429 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

new_handler & set_new_handler

阅读更多

//the discriptions in msdn ,we can find this document in

//website:http://msdn.microsoft.com/library/default.asp?url=/library/en-//us/vcstdlib/html/vclrf_new_setnewhandler.asp

Return Value

0 on the first call and the previous new_handler on subsequent calls.

Remarks

The function stores _Pnew in a static new handler pointer that it maintains, then returns the value previously stored in the pointer. The new handler is used by operator new(size_t).

Example

// new_set_new_handler.cpp
// compile with: /EHsc
#include<new>
#include<iostream>

using namespace std;
void __cdecl newhandler( )
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //__cdecl程序的压栈方式为C风格
//__stdcall为PASCAL风格
//举个例子:
//(1) C函数 Fun1(a,b,c)
// 函数调用时,参数压栈顺序为 c , b , a
//(2) PASCAL函数 Fun(a,b,c)
// 函数调用时,参数压栈顺序为 a, b , c { cout << "The new_handler is called:" << endl; throw bad_alloc( ); return; } int main( ) { set_new_handler (newhandler); try { while ( 1 ) { new int[5000000]; cout << "Allocating 5000000 ints." << endl; } } catch ( exception e ) { cout << e.what( ) << " xxx" << endl; } }

Sample Output

Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
Allocating 5000000 ints.
The new_handler is called:
bad allocation

以上例子程序在VC6.0环境下不能编译通过,但在dev_c++中可以通过编译,虽然没试过但相信在gcc下同样可以实现。如果在VC6.0环境下编译,那么必须用_set_new_handler而非set_new_handler, 下面是一个c风格的使用例子。

Example

/* HANDLER.CPP: This program uses _set_new_handler to 
 * print an error message if the new operator fails.
 */

#include <stdio.h>
#include <new.h>

/* Allocate memory in chunks of size MemBlock. */
const size_t MemBlock = 1024;

/* Allocate a memory block for the printf function to use in case
 * of memory allocation failure; the printf function uses malloc.
 * The failsafe memory block must be visible globally because the
 * handle_program_memory_depletion function can take one 
 * argument only.
 */
//非常值得注意的是在这个地方,当内存分配时如果你需要打印提示信息,而打印的步骤也是需要内存的,为防止
//连打印错误信息所需的内存都没有的窘态,必须事先先开辟一块内存以备不时之需,在内存不足需打印信息时可先放掉
//这块预留内存,这就是failsafe的用处所在。具体的请参考msdn中关于_set_new_handler的说明,以及Scott Mayers
在effective c++ 2e iterm7中相关的说明
char * failsafe = new char[128];

/* Declare a customized function to handle memory-allocation failure.
 * Pass this function as an argument to _set_new_handler.
 */
int handle_program_memory_depletion( size_t );

void main( void )
{
   // Register existence of a new memory handler.
   _set_new_handler( handle_program_memory_depletion );
   size_t *pmemdump = new size_t[MemBlock];
   for( ; pmemdump != 0; pmemdump = new size_t[MemBlock] );
}

int handle_program_memory_depletion( size_t size )
{
   // Release character buffer memory.
   delete failsafe;
   printf( "Allocation failed, " );
   printf( "%u bytes not available.\n", size );
   // Tell new to stop allocation attempts.
   return 0;
}

Output

Allocation failed %0 bytes not available.

分享到:
评论

相关推荐

    C++ 内存分配处理函数set_new_handler的使用

    new_handler set_new_handler(new_handler new_p) throw(); //C++98 new_handler set_new_handler (new_handler new_p) noexcept; //C++11 二、函数介绍 该函数的作用是:当new操作或new[]操作失败时调用参数所指...

    ortp wince

    ortp_set_log_handler ortp_strdup_printf ortp_logv ortp_get_global_stats ortp_global_stats_display session_set_new session_set_select session_set_destroy rtp_stats_display rtp_session_...

    Android 下拉刷新

    new Handler().postDelayed(new Runnable() { public void run() { // infoList.clear(); swipeLayout.setRefreshing(false); ItemInfo info = new ItemInfo(); for (int i = 0; i ; i++) { ...

    C++编程中new运算符的使用学习教程

    new运算符用作从自由存储为 type-name 的对象或对象数组分配... 通过编写自定义异常处理例程并调用 _set_new_handler 运行库函数(以您的函数名称作为其参数),可以更改此默认行为。 有关如何在托管堆上创建对象的信

    BluetoothDemoV1.2

    private Handler _handler = new Handler(); ArrayAdapter&lt;String&gt; adapter = null; /* 请求打开蓝牙 */ @SuppressWarnings("unused") private static final int REQUEST_ENABLE = 0x1; private static final ...

    最新PCSC CCID 测试源码

    最新的PCSC、CCID以及测试源码。 贴一段源码: ... * Propagate new state to reader state */ rContext-&gt;readerState-&gt;readerSharing = rContext-&gt;contexts; PROFILE_END return SCARD_S_SUCCESS; }

    BluetoothDemo

    private Handler _handler = new Handler(); ArrayAdapter&lt;String&gt; adapter = null; /* 请求打开蓝牙 */ @SuppressWarnings("unused") private static final int REQUEST_ENABLE = 0x1; private static final ...

    大名鼎鼎SWFUpload- Flash+JS 上传

     swfu = new SWFUpload({  upload_url : "http://www.swfupload.org/upload.php",  flash_url : "http://www.swfupload.org/swfupload_f9.swf", file_size_limit : "20480"  });  };  以下是一个标准的...

    sqlite3在Visual studio 2012下的编译

    File &gt; New &gt; Project. Under Project Types, select Visual C++ Projects and then Win32. Choose the project template "Win32 Project". Give the project a name and click OK. When the "Win32 ...

    dpdk-18.02.2-stable

    Added support for ACTION_PORT_ID, ACTION_DROP, ACTION_OF_POP_VLAN, ACTION_OF_PUSH_VLAN, ACTION_OF_SET_VLAN_VID, ACTION_OF_SET_VLAN_PCP and ITEM_PORT_ID. Added support for 32-bit compilation. Added ...

    DPDK-18.08-rc03

    Added support for ACTION_PORT_ID, ACTION_DROP, ACTION_OF_POP_VLAN, ACTION_OF_PUSH_VLAN, ACTION_OF_SET_VLAN_VID, ACTION_OF_SET_VLAN_PCP and ITEM_PORT_ID. Added support for 32-bit compilation. Added ...

    simple-signal-用于Rust项目的简单unix信号处理程序-Rust开发

    simple-signal一个简单的包装程序,...simple_signal :: set_handler(&[Signal :: Int,Signal :: Term],移动| _signals | {r.store(false,Ordering :: SeqCst);}); println!(“正在等待信号...”); 在运行时

    php.ini-development

    example, if you set output_handler to "mb_output_handler", character ; encoding will be transparently converted to the specified encoding. ; Setting any output handler automatically turns on output ...

    encryptedSession-PHP:增加对流行攻击的预防,如会话劫持或会话固定。 使用算法 MCRYPT_RIJNDAEL_256 通过 mcrypt 加密数据

    session_set_save_handler ( $ session , true );$ status = $ session -&gt; start (); 您还可以检查start()方法返回的状态 $ status == 'EXPIRED' # =&gt; session expired$ status == 'LOGGED' # =&gt; new session starte

    ( ap6181_sina33m_sc3817r验证通过_20170710_1608没有外层目录.7z

    # Set indication (checked by vold) that we have finished this action setprop vold.post_fs_data_done 1 # to force to start sdcard # class_start late_start # This module write data to /data should...

    VC托盘程序

    #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_DYNAMIC(CSystemTray, CObject) ///////////////////////////////////////////////// // CSystemTray ...

    简易的播放器

    #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void...

    ap6212a0_a33_sc3817r_服务器验证通过_bt已经通了_wifi需要修改配置_需要再次验证_20170626_1549.7z

    [ 4.053550] Registering SWP/SWPB emulation handler [ 4.059269] [rfkill]: rfkill set power 1 [ 4.063652] gpio ap6xxx_bt_regon set val 0, act val 0 正常启动的BT加载: [ 3.207764] Bluetooth: HCI UART ...

    文字与图片合成图片代码

    // TODO: Add your control notification handler code here } BOOL CAddTextDlg::SetBmpFilePath(LPCTSTR pszPath) { if (0 == _mbstrlen(pszPath)) { return FALSE; } m_strBmpFilePath = pszPath; ...

Global site tag (gtag.js) - Google Analytics