The new operator with the nothrow option still throws an exception

There is a code like this:

#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; } 

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

Edit:

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

+6
source share
3 answers

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

+1
source

0 must be formatted as "0" . It takes a few bytes; I bet that is the reason. Put a breakpoint on std::bad_alloc::bad_alloc and you will understand it for sure.

+7
source

This explains why he still quits and how you can make him not quit. nothrow seems to be just ignored.

If you still need a new version for the runtime library, link your program with nothrownew.obj. However, when you contact nothrownew.obj, the new one in the C ++ standard library will no longer function.

I found a rather detailed article about this, but it is dated (VC 6), but perhaps the problem still persists. BTW VC ignores all specifications of throw() functions.

When the new operator (std :: nothrow) throws an exception anyway

-2
source

Source: https://habr.com/ru/post/898069/


All Articles