|
-
March 16th, 2003, 07:15 AM
#1
letting new operator return NULL;
Hi Folks...
how can I make the new-operator return null, if something fatal in the constructor happens?
Greets
Seb
-
March 16th, 2003, 08:49 AM
#2
beaver,
I do not fully understand the question. Perhaps the nothrow version of the operator new would be useful.
Sincerely, Chris.
Code:
#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;
}
You're gonna go blind staring into that box all day.
-
March 16th, 2003, 10:31 AM
#3
Use exeptions
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
}
....
-
March 16th, 2003, 12:55 PM
#4
Override the new Operator
Code:
inline void* operator new( unsigned int size )
{
return NULL;
}
cu
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|