Using std::bad_alloc for C pointers
- by otibom
I'm using a library written in C in a C++ project.
I'd like to use C++ exceptions to handle C errors. In particular, it would be nice to have an exception thrown if an allocation fails.
I can do this in constructors of classes which hold C-style pointers to C structs :
if (c_object == NULL)
throw std::bad_alloc();
But if the class is responsible for several C objects they are no ways of free-ing all already allocated pointers since the destructor isn't called.
I have a feeling I could use smart-pointers, but I don't have much experience with them. What's more, I have to have access to the original C pointers to use the C api properly.
Is there an elegant solution to this ?