Hi all,
When operator new fails bad::alloc exception is thrown.
Does the c++ standard guarantee that the pointer will be set to NULL ?
Many thanks
Printable View
Hi all,
When operator new fails bad::alloc exception is thrown.
Does the c++ standard guarantee that the pointer will be set to NULL ?
Many thanks
No. Anyway, because of the exception, the pointer would be left unchanged.
AFAIK, when exception was thrown, stack unwinding is happen and all the local copy get destroyed. Why you said the pointer was unchanged ?
Does it related to new allocate memory on heap ?
Thanks.
If the exception causes control to reach a point where the pointer goes out of scope, then yes, the pointer would be destroyed. However, it is not necessarily the case that the pointer will go out of scope since it could be assigned to in a try block where the exception is caught in the catch block.Quote:
Originally Posted by Peter_APIIT
Sorry for my stupidity.
Do you have any example code that explain your idea ?
Thanks.
Well, a simple but rather silly example for some type T:Quote:
Originally Posted by Peter_APIIT
My main point is that because the exception is thrown, the assignment does not take place, so the pointer retains its value. If the pointer happens to be destroyed immediately after that, so be it.Code:T* p = 0;
try
{
p = new T;
}
catch (const std::exception&)
{
// do nothing
}
delete p;
Thanks you!
EDIT: How do I mark the message as a resolved?? Thank you
You're welcome :)
You can use the thread tools to mark the thread as resolved.
Just a complement...
Still, it's possible to use new in the "old" form. This is done with the nothrow version of new and is guaranteed by the Standard to return 0 in case of failure.
Code:SomeType p = new (std::nothrow) SomeType;
if (!p)
{
//Failure...
}
Watch out from std::nothrow() when there is a chance that your code may be used in environments that define thier own version of new operayor (MFC for example).
http://www.codeguru.com/forum/showthread.php?t=470168