new 和 new(std::nothrow)
2016-11-10 10:02
239 查看
源码方面的信息就不详细讲述了,找找代码看看便知,简要说明下:
new(std::nothrow) 顾名思义,即不抛出异常,当new一个对象失败时,默认设置该对象为NULL,这样可以方便的通过if(p == NULL) 来判断new操作是否成功
普通的new操作,如果分配内存失败则会抛出异常,虽然后面一般也会写上if(p == NULL) 但是实际上是自欺欺人,因为如果分配成功,p肯定不为NULL;而如果分配失败,则程序会抛出异常,if语句根本执行不到。
因此,建议在c++代码中,凡是涉及到new操作,都采用new(std::nothrow),然后if(p==NULL)的方式进行判断
new(std::nothrow) 顾名思义,即不抛出异常,当new一个对象失败时,默认设置该对象为NULL,这样可以方便的通过if(p == NULL) 来判断new操作是否成功
普通的new操作,如果分配内存失败则会抛出异常,虽然后面一般也会写上if(p == NULL) 但是实际上是自欺欺人,因为如果分配成功,p肯定不为NULL;而如果分配失败,则程序会抛出异常,if语句根本执行不到。
因此,建议在c++代码中,凡是涉及到new操作,都采用new(std::nothrow),然后if(p==NULL)的方式进行判断
相关文章推荐
- new && new(std::nothrow)
- new(std::nothrow) 和 new() 的区别
- new(std::nothrow) 和 new
- new(std::nothrow) 应用场景
- new(std::nothrow)
- new && new(std::nothrow)
- 在内存不足时,new (std::nothrow)并不抛出异常,而是将指针置NULL
- new (std::nothrow) 与 new
- new(std::nothrow) 应用场景
- 关于 new(std::nothrow)
- new (std::nothrow) 与 new
- 关于std::nothrow
- std::nothrow
- 实战c++中的智能指针unique_ptr系列-- std::unique_ptr的构造(尽量使用C++14中的std::make_unique,而不是new)
- C++学习之new返回值的误用-new(nothrow)
- 实战c++中的智能指针unique_ptr系列-- std::unique_ptr的构造(尽量使用C++14中的std::make_unique,而不是new)
- new (nothrow) T() 的原理
- could be 'void *operator new(size_t,const std::nothrow_t &) throw()'
- std::set_new_handler
- Visual Stdio 2008 最大内存分配块大小问题: 使用new 分配连续723M内存 出错 std::bad_alloc at memory location 0x0013e0b8