帮助我使这段代码异常安全

ceo*_*ceo 1 c++ exception smart-pointers container-managed

所以我有这个库代码,请看......

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_;
}
Run Code Online (Sandbox Code Playgroud)

在我的客户端代码中......

   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
Run Code Online (Sandbox Code Playgroud)

我坚持的是异常安全.就目前而言,如果任何Obj构造函数抛出,或者Thing构造函数抛出,则向量中的Objs将泄漏.向量需要包含指向Objs的指针,因为它们是以多态方式使用的.而且,我需要在这里处理任何异常,因为这是从一个不知道异常的旧代码库调用的.

在我看来,我的选择是:

  1. 将客户端代码包装在一个巨大的try块中,并清理catch块中的向量.
  2. 在所有分配周围放置try块,其catch块调用公共清理函数.
  3. 一些聪明的基于RAII的想法,我还没有想到.
  4. 平底船.实际上,如果构造函数抛出,应用程序即将崩溃,但我想更优雅地处理它.