C

C ++でnewとstd :: nothrowを使用すると、例外のスローが回避されます



Use New Std



私は常にnewを使用しますが、メモリ割り当てが失敗したときに例外を直接報告します。それに対処する方法、私は他の人の話を聞くときにstd :: nothrowを知っています。

このインタビューは間違いなくハイライトであり、ゼロ以外のポインターのチェックが実装されています。



最近発見されたばかり http://www.cplusplus.com それは良いことです。

'new(std :: nothrow)'は、メモリ割り当てが失敗したときにnullポインタを返します。 std :: bad_allocをトリガーする代わりに、Test-for-NULLチェックを簡単に実行できます。



//// bad_alloc example #include // std::cout #include // std::bad_alloc int main() { char *p= NULL int i = 0 do { p = new (std::nothrow) char[1024 * 1024] //1M each time i++ } while (p) if (NULL == p) { Std::cout << 'Assigned ' << i - 1 << 'M memory' // allocated 1890 Mn memory 1891th memory allocation failed << ' ' << i << 'The memory allocation failed' } long num = 0x7fffffff //0x7fffffff = 2,147,483,647 = 2047*1024*1024 = 2047M char* myarray = nullptr //vs2015 x86 error C2148: The total size of the array must not exceed 0x7fffffff bytes myarray = new (std::nothrow)char[2047 * 1024 * 1024] ///1024 * 1024 * 1024 if (nullptr == myarray) { Std::cerr << ' new (std::nothrow)char[2047 * 1024 * 1024] memory allocation failed' << std::endl } else { Std::cout<<' new (std::nothrow)char[2047 * 1024 * 1024] Memory allocation succeeded << << std::endl } return 0 }