On Fri, 16 Sep 2011 11:42:36 -0700, Максим Фомин wrote:
> What is best way to deal whis this?
C++ and RAII
> There is obvious solution to free all
> previous allocated resources within "if" test block of each element,
> however I am looking for a better solution.
One solution not mentioned so far is:
obj = obj_alloc();
if (!obj)
goto fail0;
obj->res1 = res1_alloc();
if (!obj->res1)
goto fail1;
obj->res2 = res2_alloc();
if (!obj->res2)
goto fail2;
...
return obj; /* success */
...
fail3:
res2_free(obj->res2);
fail2:
res1_free(obj->res1);
fail1:
obj_free(obj);
fail0:
return NULL;
Personally, I'd just go with having all of the _free() functions ignore
NULL pointers, so that you can legitimately call the top-level obj_free()
function on a partially-constructed object.