2

I know doing a new(std::no_throw) will set pointer to NULL if it failed. I also know that a normal new will throw a std::bad_alloc exception if it failed.

Will the normal new also set the pointer to NULL if it throws? Or should I set it to NULL in the catch() block?

ymoreau
  • 3,402
  • 1
  • 22
  • 60
Pubby
  • 51,882
  • 13
  • 139
  • 180

2 Answers2

6

In C++ a bad new will throw an exception (unless you use std::nothrow) and the pointer will not be assigned so it'll be whatever it was before the new call was made.

However, you may be interested in this article which talks about forcing new to return null on failure as you mentioned in your question.

Andrew White
  • 52,720
  • 19
  • 113
  • 137
0

When an exception is thrown, the stack is unwound (running destructors of local objects) until a catch stops the exception. There's nothing that automatically sets the pointer to NULL, and it's unilkely that one of the destructors does so - it would be a contrived example that did.

Usually, there's no need to set the pointer to NULL. In fact, often you can't. Take the following code:

try { 
  std::string s("hello, world");
} catch (std::bad_alloc) {
 // ???
}

It's possible that the allocation of those 12 bytes fails. The exception will return from the constructor of std::string. At that point, the object s no longer exists, nor does the pointer s._SomeInternalName inside s. The compiler will therefor report an error if you try to use s in the catch block. And if the pointer doesn't exist anymore, you obviously can't set it to 0.

MSalters
  • 173,980
  • 10
  • 155
  • 350