开发者

Operator new with nothrow option still throws exception

There is such code:

#include &开发者_StackOverflow社区lt;iostream>

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

However, this program still throws std::bac_alloc exception, altough new is called with std::nothrow parameter. This program is compiled in Visual C++ 2010. Why the exception is thrown?

Edit:

Using g++ on Windows from mingw, everything works ok.


0 has to be formatted as "0". That's going to take a few bytes; I'll bet that's the cause. Put a breakpoint on std::bad_alloc::bad_alloc and you will know for sure.


I just ran your sample from VC2010. It is not new(nothrow) that throws, but __security_check_cookie.


This explains why it is still throwing and how you can make it not throw. It seems nothrow is just ignored.

If you still want the non-throwing version of new for the C Runtime Library, link your program with nothrownew.obj. However, when you link with nothrownew.obj, new in the Standard C++ Library will no longer function.

I found an quite in depth article about this but it's kinda dated (VC 6) but maybe the problem still persists. BTW VC ignores all throw() specifications of functions.

When Operator new(std::nothrow) Throws an Exception Anyway

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜