(nothrow) = ? (C++)

Jones
Unregistered
 
Post: #1
I was perusing the cplusplus.com docs looking for tips on safer memory management, and I noticed in this example the use of the '(nothrow)' argument to the new command.

Example.

They seem to say that this '(nothrow)' tag is necessary for the command to return 0 or NULL on failure.

I had always assumed that like malloc, new would return NULL on failure automatically. This was a bit of a shock. So I went through some of my code adding this new tag, but it won't compile. It says that 'nothrow' is an unexpected argument or un-declared.

I use the tag just like in the example, so what's wrong? Annoyed

This should be easy to solve, I hope.
Thanks for any solution you can offer. Smile
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #2
Code:
$ cat > test.cpp
#include <memory>
int *foo() { return new(std::nothrow) int(5); }

$ g++ -c -Wall -W -Wno-unused-parameter -Werror test.cpp

works for me...
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #3
Incidentally, it's pretty unusual that you'd actually want to do this. The default behavior of throwing std::bad_alloc is much more useful.
Quote this message in a reply
Jones
Unregistered
 
Post: #4
OneSadCookie Wrote:Incidentally, it's pretty unusual that you'd actually want to do this. The default behavior of throwing std::bad_alloc is much more useful.

A lot of my code has already been structured to check for NULL returns, so this *might* be faster.

The problem was that I was unawares that 'nothrow' was part of std.

Thanks! Smile
Quote this message in a reply
Jones
Unregistered
 
Post: #5
Apparently, nothrow is not a member of std. Annoyed

Code:
/Users/gareth/Desktop/Mesh/OpenGL/../Mesh.cpp:36: error: 'nothrow' is not a member of 'std'

EDIT: Resolved. Smile
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #6
Don't just say "fixed it"; explain what was wrong and what you changed so that people who have the same problem in the future can benefit!
Quote this message in a reply
Jones
Unregistered
 
Post: #7
OneSadCookie Wrote:Don't just say "fixed it"; explain what was wrong and what you changed so that people who have the same problem in the future can benefit!

I forgot to include <memory>. Blush
Quote this message in a reply
Post Reply