c++: handle no memory situation

  • Thread starter Newsnet Customer
  • Start date
N

Newsnet Customer

Hi,

consider this:

void test ()
{
A* anA = new A();
if (anA == 0){//handle situation}
}

Apparenly new versions of C++ throw a bad_alloc exception and the older
versions return a null pointer value. My question is, what should you test
for if you don't know which version of c++ your using?


sasas
 
J

Josephine Schafer

Newsnet Customer said:
Hi,

consider this:

void test ()
{
A* anA = new A();
if (anA == 0){//handle situation}
}

Apparenly new versions of C++ throw a bad_alloc exception and the older
versions return a null pointer value. My question is, what should you test
for if you don't know which version of c++ your using?

There is only one standard version of C++ in which new throws a bad_alloc
exception when memory allocation fails. If your compiler returns null on
failure then it's non conforming to the C++ standard.
The way new operator can return null on failure( in standard C++ ) is by
using nothrow.

MyClass *anObject = new(nothrow) MyClass; // returns null on failure
if (NULL == anObject)
{

}

HTH,
J.Schafer
 
N

Newsnet Customer

There is only one standard version of C++ in which new throws a bad_alloc
exception when memory allocation fails. If your compiler returns null on
failure then it's non conforming to the C++ standard.
The way new operator can return null on failure( in standard C++ ) is by
using nothrow.

MyClass *anObject = new(nothrow) MyClass; // returns null on failure
if (NULL == anObject)
{

}

Cheers. That cleared it all up.


sasas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,836
Latest member
BuyBlissBitesCBD

Latest Threads

Top