Reputation: 457
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?
Upvotes: 10
Views: 2781
Reputation: 38287
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.
Upvotes: 6
Reputation:
No, it won't be. The nothrow
only applies to the call to new
, not to the constructor.
Upvotes: 16
Reputation: 347436
Foo
's constructor can still throw exceptions and they will fall through.
The constructor is not called until after the memory is allocated.
Upvotes: 11