• 11
• 9
• 10
• 9
• 10

# Checking the return value of new

This topic is 4685 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I'm working my way through Scott Meyer's "Effective C++". In one of the items, he spent a long time talking about how you should check the return value of new. However, when I tried this in VC++, it threw an exception. So, I don't think checking the return value really helps, right? The program won't ever get that far because of the exception. (unless you've disabled exceptions, I guess) Meyer did mention that some compilers are starting to adopt the practice of throwing exceptions (in addition to returning NULL), but as far as I can tell, this isn't really an enforced standard. So, what would be a good way to handle checking for new which is compiler/platform independent? It seems way too much trouble to do something like this every time you wanted to allocate some memory:
try
{
p = new char[500];

if( !p )
{
Log( "Ran out of memory" );
abort();
}
}
catch
{
Log( "Ran out of memory" );
abort();
}
I'd really appreciate any ideas or hints. Thanks! roos

##### Share on other sites
That book must be getting out of date [smile].

There are two forms of each global new operators provided by default, one which throws std::bad_alloc (and has an exception specification) another version that does not throw exceptions but returns 0 to indiciate failure (it has a no throw exception specification) this is standard, if you want the no throw version its:

#include <new> // std::nothrowchar* f = new(std::nothrow) char[500];delete[] (std::nothrow, f);

All delete operators never throws (and have no throw exception specifications) but you should still be consistant with new/delete pairs, make sure they match for defined behaviour.

If your using VC++ 6.0, time to get an update to date more standard compliant compiler [grin].

##### Share on other sites
Yeah, the book is pretty old :)

Thanks for telling me about std::nothrow, that sounds exactly like what I was looking for!

Edit: btw, I am using .NET 2k3

roos

##### Share on other sites
You might wanna go through my last post again as i made some mistakes before that i've just corrected [smile]

##### Share on other sites
Another thing to consider is that if you get a NULL or the
exception is thrown, your application is in big trouble
anyhow...

What is to guarantee the Log(...) will succeed? [smile]

##### Share on other sites
Quote:
 Original post by snk_kidThat book must be getting out of date.

A new edition just came out about a month and a half ago. Haven't really looked at it yet, but it's got about 70 more pages than the 2nd edition and apparently has had some of it rewritten to reflect the times.