抛出一个 boost::shared_ptr<自定义异常>

发布于 2024-10-20 14:21:08 字数 224 浏览 5 评论 0原文

是否存在以下任何陷阱;

 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

倾城月光淡如水﹏ 2024-10-27 14:21:08

您应该避免通过指针抛出,并且更喜欢通过值抛出通过(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.

残花月 2024-10-27 14:21:08

是的,有一个陷阱。您将无法基于基类进行捕获:

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
}

您当然可以将其抛出到基类上,但是您将无法捕获派生类。

所以是的...不要这样做。

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.

飘然心甜 2024-10-27 14:21:08

我看到的唯一陷阱是,当你不必要的时候,你正在以艰难的方式做某事。 :-)

通常,您使用共享指针来管理对象的生命周期,否则这并不明显。这里很明显,管理抛出的异常不是的责任。编译器必须为你做这件事!

当异常被处理时,运行时将销毁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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文