抛出一个 boost::shared_ptr<自定义异常>自定义异常>
是否存在以下任何陷阱;
if (someCondition)
throw boost::shared_ptr<SomeException>( new SomeException( "foo!" ) );
...
catch( const boost::shared_ptr<SomeException>& expRef )
{
}
is there any pitfall of the following;
if (someCondition)
throw boost::shared_ptr<SomeException>( new SomeException( "foo!" ) );
...
catch( const boost::shared_ptr<SomeException>& expRef )
{
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该避免通过指针抛出,并且更喜欢通过值抛出 和通过(const)引用捕获。
使用智能指针是在使用指针时简化资源管理的一种方法,但是如果您可以完全避免使用指针,那么这样做会更简单。只需抛出一个值即可。
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:
You could of course make it throw on base, but then you can't catch the derived.
So yeah...don't do it.
我看到的唯一陷阱是,当你不必要的时候,你正在以艰难的方式做某事。 :-)
通常,您使用共享指针来管理对象的生命周期,否则这并不明显。这里很明显,管理抛出的异常不是您的责任。编译器必须为你做这件事!
当异常被处理时,运行时将销毁shared_pointer,然后销毁异常对象。否则运行时会直接销毁异常对象!你有什么收获?
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?