3

我的 C++ 类聚合了一个辅助对象,它可能会在构造函数中抛出异常,但我自己的类不能抛出(我自己的类被一个框架使用,该框架没有为构造函数抛出的异常做好准备)。现在我通过创建对象来延迟辅助对象的构建来减轻这种风险,new以便我能够捕获任何异常:

struct HelperObject {
  HelperObject() {
    throw 0;
  }
}

struct MyObject {
  HelperObject *o;
  MyObject() : o( 0 ) {
    try {
      o = new HelperObject;
    } catch ( ... ) {
      // ...
    }
  }
};

但是,为此滥用有点烦人new;我突然不得不处理整个代码的指针,除了它让我可以更好地控制对象的构造时间之外,没有任何理由。

是否有可能在没有 ussign 的情况下达到这种效果new

4

2 回答 2

4

可以使用智能指针和额外的 MakeHelperObject 函数,以便在 HelperObject 域内完成异常。这只会使 MyObject 代码干净,但在 HelperObject 构建期间仍需要处理异常:

struct HelperObject {
  HelperObject() {
    throw 0;
  }

   static HelperObject* MakeHelperObject()
   {
     try
     {
       HelperObject* p = new HelperObject();
       return p; 
     }
     catch(const SomeException& e)
     {
      // deal with e
    }
    return NULL;
  }
};


struct MyObject {
  std::unique_ptr<HelperObject> o;
  MyObject() : o(HelperObject::MakeHelperObject())
  {
  }
};
于 2013-01-03T11:19:39.680 回答
2

Well, no, as you need to suppress the exception and you can only do that with a try block, and function try blocks won't allow you to suppress the exception. It sort of begs the question of how the framework is going to behave if it thinks it successfully constructed the object which now has a big hole in it.

You should consider using an scoped pointer to automatically deallocate the HelperObject. It makes for more resilient code.

于 2013-01-03T11:18:26.963 回答