开发者

Will using new (std::nothrow) mask exceptions thrown from a constructor?

Assume the following code:

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

'p' will equ开发者_如何学JAVAal 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?


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


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

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜