具有nothrow选项的operator new仍会抛出异常

scd*_*dmb 6 c++ exception new-operator nothrow

有这样的代码:

#include <iostream>

int main(){
    for(;;){
        int* ptr = new (std::nothrow) int;
        if(ptr == 0){
            std::cout << 0 << std::endl;
            break;
        }
    }
    std::cin.get();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,这个程序仍然抛出std :: bac_alloc异常,尽管使用std :: nothrow参数调用new.此程序在Visual C++ 2010中编译.为什么抛出异常?

编辑:

在mingw的Windows上使用g ++,一切正常.

MSa*_*ers 7

0必须格式化为"0".那将需要几个字节; 我敢打赌这是原因.断点std::bad_alloc::bad_alloc ,你肯定会知道.


Nem*_*vic 1

我刚刚运行了 VC2010 中的示例。抛出的不是 new(nothrow) ,而是__security_check_cookie