How to check memory allocation failures with new operator?

前端 未结 4 1125
囚心锁ツ
囚心锁ツ 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

    Well, you call new that throws bad_alloc, so you must catch it:

    try
    {
        scoped_array buf(new char[MAX_BUF]);
        ...
    }
    catch(std::bad_alloc&) 
    {
        ...
    }
    

    or

    scoped_array buf(new(nothrow) char[MAX_BUF]);
    if(!buf)
    {
       //allocation failed
    }
    

    What I mean by my answer is that smart pointers propagate exceptions. So if you're allocating memory with ordinary throwing new, you must catch an exception. If you're allocating with a nothrow new, then you must check for nullptr. In any case, smart pointers don't add anything to this logic

提交回复
热议问题