Using std::bad_alloc for C pointers

Posted by otibom on Stack Overflow See other posts from Stack Overflow or by otibom
Published on 2011-02-18T15:09:39Z Indexed on 2011/02/18 15:25 UTC
Read the original article Hit count: 146

Filed under:
|
|

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 ?

© Stack Overflow or respective owner

Related posts about c++

Related posts about exception