Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With "-fno-exceptions", what happens with "new T"?

Tags:

c++

exception

I was wondering, will new T still throw bad_alloc if I compile my program using the -fno-exceptions option to disable exception handling?

Or will the compiler (GCC and clang support that option) implicitly transform the use of new T to new (nothrow) T?

like image 610
Johannes Schaub - litb Avatar asked May 18 '11 18:05

Johannes Schaub - litb


People also ask

What are FNO exceptions?

Enables or disables the generation of code needed to support C++ exceptions.

How do you delete an exception in C++?

To catch and delete exceptionsUse the try keyword to set up a try block. Execute any program statements that might throw an exception within a try block. Use the catch keyword to set up a catch block. Place exception-handling code in a catch block.


2 Answers

The way I understand it, operator new is defined by libstdc++. If you now compile your own code with -fno-exceptions, you cannot catch any exceptions, but you will still be linking against the normal version of libstdc++, which does throw an exception.

So yes, new T will throw an exception, even with -fno-exception.

However, if you compiled libstdc++ with -fno-exception as well, things become different. Now, new T cannot throw an exception but, if I read the libstdc++ manual right it will call abort() instead.

It seems that, if you want your new T to return NULL on failure, the only way is to explicitely specify nothrow...

like image 183
Matthijs Kooijman Avatar answered Oct 12 '22 05:10

Matthijs Kooijman


I can't give a definitive answer to all the perks around -fno-exceptions, just the observations on a 32 bit linux machine, gcc 4.5.1 - bad_alloc is thrown with and without -fno-exceptions

[21:38:35 1 ~/tmp] $ cat bad_alloc.cpp  int main() {     char* c = new char[4000000000U]; } [21:38:58 1 ~/tmp] $ g++ bad_alloc.cpp [21:39:06 1 ~/tmp] $ ./a.out terminate called after throwing an instance of 'std::bad_alloc'   what():  std::bad_alloc Aborted [21:39:07 1 ~/tmp] $ g++ -fno-exceptions bad_alloc.cpp [21:39:16 1 ~/tmp] $ ./a.out terminate called after throwing an instance of 'std::bad_alloc'   what():  std::bad_alloc Aborted 
like image 22
nos Avatar answered Oct 12 '22 06:10

nos