美文网首页
new(std::nothrow)

new(std::nothrow)

作者: Otis4631 | 来源:发表于2022-07-20 14:00 被阅读0次

new(std::nothrow) 顾名思义,即不抛出异常,当new一个对象失败时,默认设置该对象为NULL,这样可以方便的通过if(p == NULL) 来判断new操作是否成功

普通的new操作,如果分配内存失败则会抛出异常,虽然后面一般也会写上if(p == NULL) 但是实际上是自欺欺人,因为如果分配成功,p肯定不为NULL;而如果分配失败,则程序会抛出异常,if语句根本执行不到。

因此,建议在c++代码中,凡是涉及到new操作,都采用new(std::nothrow),然后if(p==NULL)的方式进行判断

rec = new (std::nothrow) ClassA();
if (NULL == rec) {
}

转自:https://blog.csdn.net/qq_42604176/article/details/122825081

相关文章

  • new(std::nothrow)

    new(std::nothrow) 顾名思义,即不抛出异常,当new一个对象失败时,默认设置该对象为NULL,这样...

  • C++标准库常用内容

    nothrow 缘起在C++中使用new 创建新对象时可能会因为某个原因引起内存分配失败从而抛出 std::bad...

  • cpp中 new用法注意点

    new有三种使用方式:plain new,nothrow new和placement new。 (1)plain ...

  • ch10

    【相关文档】1.c++中的#include C++中nothrow的介绍及使用 【相关文档】1.C++ ...

  • c++学习记录5(GeekBand)

    说说new的六种重载形式: 全局的new有六种重载形式, void *operator new(std::size...

  • GeekBand C++第五周

    new的六种重载形式: 全局的new有六种重载形式, void *operator new(std::size_t...

  • 智能指针

    1. share_ptr 使用 必须显示调用 std::shared_ptr ptr(new String("...

  • C++并发高级接口:std::async和std::future

    目录 std::async和std::future   std::launch::async   std::lau...

  • C++并发编程原理

    C++11多线程API std::thread std::mutex std::future std::async...

  • [C++]string 切割

    std::vector split(std::string str, std::string pattern){...

网友评论

      本文标题:new(std::nothrow)

      本文链接:https://www.haomeiwen.com/subject/wfgeirtx.html