I just came across a problem where the constructor of a class needs to allocate memory. So I happily wrote char *mem = static_cast<char*>(malloc(100*sizeof(*mem)));
. But then I suddenly realized that in case of error I can't return error code (I am not using exceptions in my code). How can I solve this problem?
Should I add an bool initialized
member and then after making my class and then check it right after, as in:
myClass mc;
if (!mc.initialized) {
printf("Memory allocation failed in mc's constructor\n");
exit(1);
}
Thanks, Boda Cydo.
You should use new, not malloc. new throws std::bad_alloc when you are out of memory. An exception should be propagated from the constructor if you fail to allocate (or for any other reason have a problem with initialization), as this is the only way you prevent the destructor from being called. If the constructor successfully completes, the destructor must be called (unless, of course, it was heap allocated and never freed).
That's what exceptions were invented for. Also, use new
instead of malloc(3)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With