Michael said:
Could you tell me how to under the following statements? Does it mean
each and every memory allocation will check all the pointer no matter a
null pointer or not? Right? Thanks in advance!
This nothrow method requires more work than the exception method, since
the value returned has to be checked after each and every memory
allocation.
It means that there are two methods: a nothrow method, which doesn't
emit any exceptions, and a throwing method, which may emit an
exception. Presumably, both methods return a pointer to something, but
the nothrow method might return a null pointer to indicate failure,
while the throwing method will always return a valid pointer since it
will throw an exception on failure instead. Here's an example:
#include <iostream>
#include <new>
#include <cstdlib>
struct A
{
static A* Create( const std::nothrow_t& ) throw()
{
A* a = new( std::nothrow ) A;
return a; // might be null
}
static A* Create()
{
A* a = new A;
return a; // guaranteed to be non-null; see FAQ 16.6
}
// ...
};
void Foo()
{
A* const a1 = A::Create( std::nothrow );
if( !a1 )
{
std::cerr << "Doh! Couldn't create a1." << std::endl;
std::exit( -1 ); // or whatever
}
A* const a2 = A::Create( std::nothrow );
if( !a2 )
{
std::cerr << "Doh! Couldn't create a2." << std::endl;
std::exit( -1 ); // or whatever
}
// Finally, we can use a1 and a2
}
void Bar()
{
try
{
A* const a1 = A::Create();
A* const a2 = A::Create();
// Use a1 and a2 here.
}
catch( const std::exception& e )
{
std::cerr << "Doh! " << e.what() << std::endl;
std::exit( -1 ); // or whatever
}
}
See FAQ 17.1 on the why of using exceptions. The gist: When we have
multiple statements that could fail, the exception approach is often
cleaner because it avoids a bunch of if-statements that clutter the
flow and logic of the code and means the user can't ignore the error
(intentionally or not).
Cheers! --M