Stefano Falasca
Stefano Falasca

Reputation: 9097

what does it mean for `new` to be no-throw guaranteed when bad_alloc is not thrown

From the documentation of new:

The first version (1) throws bad_alloc if it fails to allocate storage. Otherwise, it throws no exceptions (no-throw guarantee).

To me, this should mean that this code

#include <new>

struct A{
    A(){
        throw 0;
    }  
};

int main(){
    try{
        A* a = new A;
    }
    catch(std::bad_alloc&){}
}

is perfectly fine. However, when compiling it with gcc (see here), the program terminates after throwing an int.

Upvotes: 1

Views: 151

Answers (3)

aschepler
aschepler

Reputation: 72431

The expression new A normally does two things:

  1. Call operator new to get some storage.
  2. Call a constructor of A to create an A object within that storage.

The quote you pasted only describes the behavior of the function ::operator new(std::size_t). Here step 2 throws an int after operator new has already succeeded and exited.

(In this example, C++ does make sure the allocated memory is passed to operator delete before you get to any catch handler.)

Upvotes: 4

IanPudney
IanPudney

Reputation: 6031

The keywordnew is no-throw guarenteed, not the class you're allocating (A). You've explicitly defined the constructor for A as throwing an exception; when an A is allocated, A throws the exception, not new.

Upvotes: 2

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234584

That's the documentation of operator new, which is not the same as the new expression. A new expression calls operator new to obtain memory and then calls the constructor requested on that memory. operator new does not throw anything other than std::bad_alloc, but the later call to the constructor can throw whatever the user code wants.

Compare new expression with operator new.

Upvotes: 11

Related Questions