Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I do if constructor fails to allocate memory in C++?

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.

like image 515
bodacydo Avatar asked Jul 05 '10 01:07

bodacydo


2 Answers

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).

like image 152
Shirik Avatar answered Nov 08 '22 19:11

Shirik


That's what exceptions were invented for. Also, use new instead of malloc(3).

like image 30
Nikolai Fetissov Avatar answered Nov 08 '22 20:11

Nikolai Fetissov