Search code examples
raiibad-alloc

How to deal with bad_alloc in RAII?


The code is as follows:

class A;
shared_ptr<A> aPtr(new A());
//do something with aPtr.

If new throws a bad_alloc exception, what happend to the smart point aPtr? Do I need to do some check with aPtr, and how to do? And I know one of the Google C++ program rules is never using exceptions, but how they deal with exceptions like bad_alloc? Thank you for any replies.


Solution

  • If you get a bad_alloc you're pretty much screwed anyway. I'm not sure how you expect to handle the allocation failing here. Not using exceptions does not really apply in this case.

    If you really want to opt out of it you can add a nothrow to that statement and it'll return nullptr instead of throwing a bad_alloc:

    shared_ptr<A> aPtr(new (std::nothrow) A());
    

    For more information see this question about the design consideration involved. Additionally see this question explainign why using std::nothrow is a bad idea.