Click to See Complete Forum and Search --> : letting new operator return NULL;
angrybeaver
March 16th, 2003, 06:15 AM
Hi Folks...
how can I make the new-operator return null, if something fatal in the constructor happens?
Greets
Seb
dude_1967
March 16th, 2003, 07:49 AM
beaver,
I do not fully understand the question. Perhaps the nothrow version of the operator new would be useful.
Sincerely, Chris.
#include <iostream>
#include <memory>
class c
{
private:
unsigned char* pb;
int some_member;
public:
c()
{
// Returns 0 if allocation fails.
pb = new (::std::nothrow) unsigned char[1024 * 1024];
if(!pb)
{
return;
}
some_member = 0;
}
~c()
{
if(pb)
{
delete [] pb;
}
}
public:
const bool valid(void) const { return pb != NULL; }
};
int main(int argc, char* argv[])
{
c C;
::std::cout << (C.valid() ? 1 : 0) << ::std::endl;
return 1;
}
Rabelo
March 16th, 2003, 09:31 AM
Returning null from an allocator is an old C style. C++ was designed to work with exeptions. On this case you use CMemoryExeption, for example:
...
try
{
CString MyString = new CString;
}
catch(CMemoryException* e)
{
deal with the error here, you can see the structure e to pick the exact reason of the error
}
....
kakalake
March 16th, 2003, 11:55 AM
Override the new Operator
inline void* operator new( unsigned int size )
{
return NULL;
}
cu
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.