最終更新日時(UTC):
が更新

履歴 編集

type-alias
<new>

std::new_handler

namespace std {
  using new_handler = void(*)();
}

概要

new失敗時に呼ばれる関数の型。set_new_handler()get_new_handler()で使用する。

new演算子は本来であれば失敗時にbad_alloc例外を送出するが、これらを使用することで、new失敗時の動作を任意の関数で置き換えられる。

ハンドラの内部では、以下のいずれかを行う必要がある:

  • 確保済みの領域を解放してreturnする
  • bad_allocまたはその派生の例外を送出する
  • returnにより処理を返すことなく、プログラムの実行を直ちに終了させる(quick_exit()exit()abort()などを使用する)

#include <iostream>
#include <new>
#include <limits>
#include <cstdlib>

void on_new_failed()
{
  // エラー理由を出力し、プログラムを異常終了させる
  std::cout << "メモリ確保に失敗した" << std::endl;
  std::abort();
}

int main()
{
  // new失敗時の動作をカスタマイズ
  std::new_handler handler = on_new_failed;
  std::set_new_handler(handler);

  int* p = new int[std::numeric_limits<std::size_t>::max()];
}

出力例

メモリ確保に失敗した

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.