How to check memory allocation failures with new operator?

前端 未结 4 1122
囚心锁ツ
囚心锁ツ 2020-12-03 10:16

Just recently I switched the language of my project to use C++ from C. With C, I used malloc and after that I check if malloc was successful but with C++, I use \'new\' to a

4条回答
  •  感动是毒
    2020-12-03 10:45

    In C++ there are 2 primary ways in which new allocates memory and each requires different error checking.

    The standard new operator will throw a std::bad_alloc exception on failure and this can be handled like a normal exception

    try {
      char* c = new char[100];
    } catch (std::bad_alloc&) {
      // Handle error
    }
    

    Or alternative the nothrow version of new will simply return NULL on failure

    char* c = new (std::nothrow) char[100];
    if (!c) {
      // Handle error
    }
    

    I'm curious though as to what you expect to do when the allocation fails? If there is no memory available to allocate your object, there's often very little which can be done in the process.

提交回复
热议问题