Re: Null pointer from "new" operator.
On Tuesday, 2 July 2013 00:47:31 UTC+3, alan_mc...@this.is.invalid wrote:
I keep seeing code of the form
(names withheld to protect the guilty :-)):
T *t = new T( arg1, ... );
if ( t )
{
// code that uses t
}
My understanding was that "new" (in contrast to malloc())
never returns a null pointer; if it can't allocate the
memory (or if the constructor fails), an exception is
thrown.
Yes, that if has been redundant for some time but possible
overloading made it dim it throws or not. In C++11 it is clear.
Their code should look like that in C++11 to have point:
T *t = new (std::nothrow) T( arg1, ... );
if ( t )
{
// code that uses t
}
So can I tell people who write code like this that the
"if" is redundant? Or are there obscure cases where
"new" might return a null pointer?
Unless it is a code base that is still maintained using MSVC 5.0
(that did not throw bad_alloc) you should certainly point it out.
(Note: class T does not override any flavor of operator new.
Also, this is not C++77 or something.)
When you override non-throwing new for T then you are expected to
write it in C++11 like that:
class T
{
public:
static void * operator new (size_t size, std::nothrow_t)
throw ();
};
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]