How to check memory allocation failures with new operator?

前端 未结 4 1124
囚心锁ツ
囚心锁ツ 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条回答
  •  猫巷女王i
    2020-12-03 10:48

    You'll still need to check for a memory allocation failure.

    Either

    scoped_array buf;
    
    try {
      buf.reset( new char[MAX_BUF] );
    } catch( std::bad_alloc& ) {
      // Handle the failure
    }
    

    Or

    scoped_array buf( new(std::nothrow)char[MAX_BUF] );
    
    if( buf.get() == NULL ) {
       // Handle the failure
    }
    

提交回复
热议问题