问题
In a school project of mine I was requested to create a program not using STL.
In the program I use alot of
Pointer* = new Something;
if (Pointer == NULL) throw AllocationError();
My question is about allocation errors:
1. is there an automatic exception thrown by new when allocation fails?
2. if so how can I catch it if I'm not using STL (#include "exception.h
)
3. is using the NULL testing enugh?
thank you.
I'm using eclipseCDT(C++) with MinGW on windows 7.
回答1:
Yes, the new operator will automatically thrown an exception if it cannot allocate the memory.
Unless your compiler disables it somehow, the new operator will never return a NULL pointer.
It throws a bad_alloc
exception.
Also there is a nothrow
version of new that you can use:
int *p = new(nothrow) int(3);
This version returns a null pointer if the memory cannot be allocated. But also note that this does not guarantee a 100% nothrow
, because the constructor of the object can still throw exceptions.
Bit more of information: http://msdn.microsoft.com/en-us/library/stxdwfae(VS.71).aspx
回答2:
- is there an autamtic exception thrown by new when allocation fails?
- if so how can I catch it if I'm not using STL (#include "exception.h)
Yes. See this example. It also demonstrates how to catch the exception!
try
{
int* myarray= new int[10000];
}
catch (bad_alloc& ba)
{
cerr << "bad_alloc caught: " << ba.what() << endl;
}
From here : http://www.cplusplus.com/reference/std/new/bad_alloc/
3 . is using the NULL testing enugh?
That is not needed, unless you overload the new
operator!
回答3:
Yes: std::bad_alloc
In my opinion, that isn't part of the STL any more that operator new is. (You could catch ... but you'll loose the possibility to descriminate with other exceptions).
It is unneeded, new will throw an exception and not return NULL.
回答4:
Standard C++ throws an exception if the requested memory cannot be allocated. If you want NULL instead of the exception then the syntax is
Whatever *p = new (std::nothrow) Whatever;
This syntax is just a case of "placement new" allocation that allows an allocator function to receive parameters.
Most of the times I've seen checking for NULL after new
is in Visual C++ code, where the default behavior of ::operator new
is to return NULL instead of raising an exception like the standard requires (this is IMO one of the many areas in which Microsoft tried (is still trying?) to fight against portable code).
回答5:
Standard new throws a bad_alloc exception on failure, so your null check isnt needed.
回答6:
It depends Old c++ compiler provide the set_new_handler to catch allocation failure. You can also catch the bad_alloc exception.
http://en.wikipedia.org/wiki/New_%28C%2B%2B%29
If you want to control this you can also override the operator new
/operator delete
pair
来源:https://stackoverflow.com/questions/4615021/bad-allocation-exceptions-in-c