Search code examples
c++exceptionsmart-pointerscontainer-managed

Help me make this code exception-safe


So I have this library code, see...

class Thing
{
public:

    class Obj 
    {
     public:
        static const int len = 16;

        explicit Obj(char *str)
        {
            strncpy(str_, str, len);
        }

        virtual void operator()() = 0;

    private:
        char str_[len];
    };

    explicit Thing(vector<Obj*> &objs) : objs_(objs) {}

    ~Thing() {
        for(vector<Obj*>::iterator i = objs_.begin(); i != objs_.end(); ++i) {
            delete *i;
        }
    }

private:
    vector<Obj*> objs_;
}

And in my client code...

   class FooObj : public Thing::Obj
    {
        virtual void operator()() {
            //do stuff
        }
    }

    class BarObj : public Thing::Obj
    {
        virtual void operator()() {
            //do different stuff
        }
    }

vector<Objs*> objs;
int nStructs = system_call(*structs);
for(int i = 0; i < nStructs; i++) {
    objs.push_back(newFooObj(structs[i].str));
}
objs.push_back(newBarObj("bar1");
objs.push_back(newBarObj("bar2");

Thing thing(objs);
// thing does stuff, including call Obj::()() on the elements of the objs_ vector

The thing I'm stuck on is exception safety. As it stands, if any of the Obj constructors throw, or the Thing constructor throws, the Objs already in the vector will leak. The vector needs to contain pointers to Objs because they're being used polymorphically. And, I need to handle any exceptions here, because this is being invoked from an older codebase that is exception-unaware.

As I see it, my options are:

  1. Wrap the client code in a giant try block, and clean up the vector in the catch block.
  2. Put try blocks around all of the allocations, the catch blocks of which call a common cleanup function.
  3. Some clever RAII-based idea that I haven't thought of yet.
  4. Punt. Realistically, if the constructors throw, the application is about to go down in flames anyway, but I'd like to handle this more gracefully.

Solution

  • Since your Thing destructor already knows how to clean up the vector, you're most of the way towards a RAII solution. Instead of creating the vector of Objs, and then passing it to Thing's constructor, you could initialize Thing with an empty vector and add a member function to add new Objs, by pointer, to the vector.

    This way, if an Obj's constructor throws, the compiler will automatically invoke Thing's destructor, properly destroying any Objs that were already allocated.

    Thing's constructor becomes a no-op:

    explicit Thing() {}
    

    Add a push_back member:

    void push_back(Obj *new_obj) { objs_.push_back(new_obj); }
    

    Then the allocation code in your client becomes:

    Thing thing(objs);
    int nStructs = system_call(*structs);
    for(int i = 0; i < nStructs; i++) {
        thing.push_back(newFooObj(structs[i].str));
    }
    thing.push_back(newBarObj("bar1");
    thing.push_back(newBarObj("bar2");
    

    As another poster suggested, a smart pointer type inside your vector would also work well. Just don't use STL's auto_ptr; it doesn't follow normal copy semantics and is therefore unsuitable for use in STL containers. The shared_ptr provided by Boost and the forthcoming C++0x would be fine.