i just would like to know Your opinion about an allocation check macro that i wrote:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#define ALLOCATION_CHECK(allocation,errormsg) \
if(!(allocation)) \
{ \
printf("%s", errormsg); \
return false; \
}
int main()
{
ALLOCATION_CHECK(somevar = new someclass, "Allocation error in main func");
//do something useful ... then free up resources
return 1;
}
Its working like charm, but i just wish to know Your opinion,
if somebody knows a better solution lets hear it !
The main goals are:
1. Have a solution where i can do allocation and its error handling within one line of code
2. Not to use exceptions because the allocation occurs on the fly in a real time application (game), where we know exception handling really slows things down.
3. Have the option to return false from the caller function straight.
These demands are satisfied, so what do You think ?
You've got a memory leak. Also, new doesn't return NULL when the allocation fails. instead, it throws an exception, which you don't handle. To make new return NULL, you have to tell it not to throw exceptions. For example:
int Memory( new( std::nothrow ) int( 10 ) );
Here, if the allocation fails, NULL is returned. If the allocation succeeds, a new integer is created and assigned the value of 10.
Exceptions are a good thing since they allow you to recover from allocation errors and such, which generally terminate the program pre-maturely.
Secondly, you never call delete on the resources you allocate. Thirdly, you never check if the given pointer is already allocating memory or pointing to some other object.
Thank You, you are right:
1. So its better to have this then: ALLOCATION_CHECK(somevar = new(std::nothrow) someclass, "Allocation error in main func");
2. I did not free up the resources, this sample is not complete, only the allocation is in focus at the moment.
3. This is also true :)
So basically i know exceptions are better, but as its said:
1. real time apps could not have it
2. not a one line solution, and exception can handle too many things, and i really need only the allocation check
It seems nobody else needs allocation with such demands :)
I also think about to override the global new/delete operator,
but in that case, i will not be able to return from function,
if something goes wrong.
What if the function has a return type of void? Your returnfalse; will create a compiler error. And possibly a warning for any return type other than bool.
It does not make too much sense to output such a message. If there's not enough memory to proceed an exception and then exit the program quickly suffice.
The only interesting thing that might help (because out of memory is certainly a bug) is the file and the line (and the compile time) to understand what happens.
So instead of putting the 'new' inside a macro make a macro out of the 'new'.
Today new fails really seldom. More interesting would be to determine where a memory leak occurs -> 'delete' as macro as well