new(std::nothrow)
2016-11-22 19:20
162 查看
转自:http://blog.sina.com.cn/s/blog_65d204330101do6r.html
源码方面的信息就不详细讲述了,找找代码看看便知,简要说明下:
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 (std::nothrow)并不抛出异常,而是将指针置NULL
- new && new(std::nothrow)
- new (std::nothrow) 与 new
- new(std::nothrow) 应用场景
- new 和 new(std::nothrow)
- 关于 new(std::nothrow)
- new (std::nothrow) 与 new
- new && new(std::nothrow)
- new(std::nothrow) 和 new() 的区别
- new(std::nothrow) 和 new
- new(std::nothrow) 应用场景
- C++之std::nothrow
- std::nothrow
- std::nothrow
- Item21 Perfer std::make_unique and std::make_shared to direct use of new
- std::nothrow .
- WINX的STD_NEW与MFC共存问题
- PHP new StdClass() 创建空对象
- c++11 条款21:尽量使用std::make_unique和std::make_shared而不直接使用new
- 比起直接使用new,更偏爱使用std::make_unique和std::make_shared