C++ td::nothrow

定義:

std::nothrow被用來作爲new操作符的一個參數。

平時使用new申請內存失敗的話會直接拋出bad_alloc異常。

如果使用new(std::nothrow)申請內存失敗的話,此時不會拋出一個異常而是返回一個空指針。

這個常量是nothrow_t的一個值,他的作用是觸發new操作符的另一個版本的重載方法(該重載方法接受一個nothrow_t類型的參數)。

默認情況下,new(std::nothrow)中,std::nothrow並不會被使用,只有在申請內存失敗時返回一個空指針。

測試程序:

// nothrow example
#include <iostream>     // std::cout
#include <new>          // std::nothrow

int main () {
  std::cout << "Attempting to allocate 1 MiB... ";
  char* p = new (std::nothrow) char [1048576];

  if (!p) {             // null pointers are implicitly converted to false
    std::cout << "Failed!\n";
  }
  else {
    std::cout << "Succeeded!\n";
    delete[] p;
  }

  return 0;
}

 如果申請內存成功,輸出:

Attempting to allocate 1 MiB... Succeeded!

如果申請內存失敗,輸出:

Attempting to allocate 1 MiB... Failed!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章