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的指针,因为它们是以多态方式使用的.而且,我需要在这里处理任何异常,因为这是从一个不知道异常的旧代码库调用的.
在我看来,我的选择是:
归档时间: |
|
查看次数: |
348 次 |
最近记录: |