Is it required to check a pointer validity if new fails?

前端 未结 4 861
轮回少年
轮回少年 2021-01-15 21:29

As title says, i know that new throws an exception which can be caught, but what exactly happens to the pointer? it turns NULL? I checked some answers on SO but none explain

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-15 22:14

    If an exception is thrown, then the pointer will not be assigned a new value. If your pointer is scoped inside of the try block where you do the allocation, or is not scoped in any try block, then the exception will cause the scope to change such that you can't access the pointer any more. Consequently, there's no need to test the pointer.

    If, on the other hand, the pointer is declared in a way where it persists after the allocation fails, then you would need to check the value. For example:

    T* ptr = NULL;
    try {
        ptr = new T();
    } catch (std::bad_alloc& ) {
        /* ... handle error */
    }
    // Have to test ptr here, since it could still be NULL.
    

    Hope this helps!

提交回复
热议问题