> If "new" fails, does it return a null pointer?
> Only if you use the nothrow version.
Evaluation of the new expression can fail for a variety of reasons.
1. Evaluation of the expression
new (std::nothrow) A[sz] may fail if
sz is invalid; in this case, the allocation function
operator new[] is not called; the implementation will throw an exception of type
std::bad_array_new_length.
2. Evaluation of the expression
new (std::nothrow) A( /*...*/ ) may fail if the allocation function could not allocate the memory. In this case, because of
std::nothrow, it returns
(void*)nullptr and
(A*)nullptr is the result of the evaluation.
3. Evaluation of the expression
new (std::nothrow) A( /*...*/ ) may fail if the the allocation function returned a non-null pointer, but the object initialisation code throws an exception. The deallocation function is called to release the memory and the exception that was thrown is propagated to the context of the
new-expression.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
#include <new>
#include <stdexcept>
struct A
{
A( int i ) { if( i > 100 ) throw std::invalid_argument( "A::A(int) - invalid constructor argument" ) ; }
};
int main()
{
try
{
int* p = new (std::nothrow) int[-1] ;
delete p ;
}
catch( const std::exception& error )
{
std::cerr << "new failed, exception was thrown. what: " << error.what() << '\n' ;
}
try
{
A* p = new (std::nothrow) A(500) ;
delete p ;
}
catch( const std::exception& error )
{
std::cerr << "new failed, exception was thrown. what: " << error.what() << '\n' ;
}
}
|
g++-4.9 -std=c++11 -Wall -Wextra -pedantic-errors -O3 main.cpp -o test && ./test
new failed, exception was thrown. what: std::bad_array_new_length
new failed, exception was thrown. what: A::A(int) - invalid constructor argument |
http://coliru.stacked-crooked.com/a/dfc0bcd9d03c6d7c
>
throw "Could not create Obj";
This will not be caught by
catch(std::string s)
. It can be caught by
catch( const char* )
.
Perhaps something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
Obj* CreateObj()
{
try
{
auto p = new Obj ;
std::clog << "created object at " << p << '\n';
return p ;
}
catch( const std::bad_alloc& )
{ std::cerr << "could not create object: allocation failed\n" ; }
catch( ... )
{ std::cerr << "could not create object: initialisation failed\n" ; }
return nullptr ;
}
|