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

后端 未结 3 1336
庸人自扰
庸人自扰 2020-12-20 14:00

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 a

相关标签:
3条回答
  • 2020-12-20 14:26

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

    0 讨论(0)
  • 2020-12-20 14:32

    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 讨论(0)
  • 2020-12-20 14:39

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

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

    0 讨论(0)
提交回复
热议问题