tags:

views:

312

answers:

3

Assume the following code:

Foo* p = new (std::nothrow) Foo();

'p' will equal 0 if we are out of heap memory.

What happens if we are NOT out of memory but Foo's constructor throws? Will that exception be "masked" by the nothrow version of 'new' and 'p' set to 0?... Or will the exception thrown from Foo's constructor make it out of the function?

+5  A: 

Foo's constructor can still throw exceptions and they will fall through.

The constructor is not called until after the memory is allocated.

Brian R. Bondy
+4  A: 

No, it won't be. The nothrow only applies to the call to new, not to the constructor.

anon
+1  A: 

I just tried it. The exception does get through. If you run the following code:

#include <new>

class Foo
{
public:
    Foo()
    {
        throw 42;
    }
};


int main()
{
    Foo* foo = new(std::nothrow) Foo;

    return 0;
}

then you get the following output (on Linux anyway):

terminate called after throwing an instance of 'int'
Aborted

So, the exception does indeed get through in spite of the nothrow.

Jonathan M Davis