c++ - Using std::bad_alloc for C pointers -
i'm using library written in c in c++ project.
i'd use c++ exceptions handle c errors. in particular, nice have exception thrown if allocation fails.
i can in constructors of classes hold c-style pointers c structs :
if (c_object == null) throw std::bad_alloc();
but if class responsible several c objects no ways of free-ing allocated pointers since destructor isn't called.
i have feeling use smart-pointers, don't have experience them. what's more, have have access original c pointers use c api properly.
is there elegant solution ?
it has been mentioned in comments, merely repeat answer:
but if class responsible several c objects no ways of free-ing allocated pointers since destructor isn't called.
that correct. because of , single-responsibility principle, each c++ class manages @ 1 unmanaged resource ("c object" in case). , classes manage resource absolutely nothing else.
if use smart pointer, that: smart pointer class manages access single type of resource, namely, heap objects allocated new
(the latter can customized). if you, feel free use smart pointer, fine, never write class manages more 1 raw resource.
Comments
Post a Comment