rookie
rookie

Reputation: 7883

Why should I check the return value of operator NEW?

Meyers in his book "50 ways to improve..." second edition writes that I must check return type of new, but I know that if operator NEW can't allocate memory it throws exception, so with newer libraries I don't need to check return value of new, am I right? thanks in advance

Upvotes: 3

Views: 2365

Answers (2)

user
user

Reputation: 7333

In general, I think you're correct: the modern libraries usually throw exceptions for this. But if you're distributing source, some compilers still return NULL rather than throwing an exception. In those situations, it can be useful, but it really depends whether you're going to be there to debug it and how critical the stability of this program is.

Also, someone else pointed out that this is such an obscure problem nowadays that the burden is on the person using the ancient compiler.

Upvotes: 2

Chubsdad
Chubsdad

Reputation: 25537

No, because C++ allows new to also return NULL on failure.

$5.3.4/13 - "[Note: unless an allocation function is declared with an empty exception-specification (15.4), throw(), it indicates failure to allocate storage by throwing a bad_alloc exception (clause 15, 18.4.2.1); it returns a non-null pointer otherwise. If the allocation function is declared with an empty exception-specification, throw(), it returns null to indicate failure to allocate storage and a non-null pointer otherwise. ] If the allocation function returns null, initialization shall not be done, the deallocation function shall not be called, and the value of the new-expression shall be null.

Upvotes: 0

Related Questions