开发者

throwing a boost::shared_ptr< customException>

is there any pitfall of the f开发者_如何学Pythonollowing;

 if (someCondition)
   throw boost::shared_ptr<SomeException>( new SomeException( "foo!" ) );

 ...

 catch( const boost::shared_ptr<SomeException>& expRef )
 {
 }


You should avoid throwing by pointer, and prefer throwing by value and catching by (const) reference.

Using a smart pointer is a way of simplifying resource management when using pointers, but if you can avoid using pointers altogether, it will be simpler doing so. Just throw a value.


Yes, there is a pitfall. You won't be able to catch based on base classes:

void f()
{
  throw std::runtime_error("look here");
}
void g()
{
  throw boost::shared_ptr<std::runtime_error>("look here");
}

int main()
{
  try
  {
    f();
  }
  catch ( std::exception const& e) {}

  try { g(); }
  catch ( boost::shared_ptr<std::exception> const& e) {} // no work
}

You could of course make it throw on base, but then you can't catch the derived.

So yeah...don't do it.


The only pitfall I can see is that you are doing something the hard way, when you don't have to. :-)

Normally you use a shared_pointer to manage the lifetime of an object, when that is not obvious otherwise. Here it is clear that it is not your responsibility to manage the exceptions thrown. The compiler will have to do that for you!

When the exception is handled, the runtime will destroy the shared_pointer that will then destroy the exception object. Otherwise the runtime would have destroyed the exception object directly! What do you gain?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜