C ++异常抛出/捕获优化 [英] C++ Exception Throw/Catch Optimizations

查看:169
本文介绍了C ++异常抛出/捕获优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,如果你有这样的C ++代码:

It seems to me that if you have some C++ code like this:

int f()
{
  try {
    if( do_it() != success ) {
      throw do_it_failure();
    }
  } catch( const std::exception &e ) {
    show_error( e.what() );
  }
}

C ++编译器应该能够优化throw

The C++ compiler should be able to optimize the throw and catch into almost a simple goto.

但是,从我的经验来看,从反汇编和逐步通过代码,编译器总是 跳过非常杂乱的异常处理库。

However, it seems to me from my experience viewing disassembly and stepping through code that the compilers always jump through the very messy exception handling libraries.

为什么要这样做?有没有阻止优化的语言要求?如果是:

Why do they do that? Is there some language requirement that prevents optimizing? What if it was:

int f()
{
  try { throw std::runtime_error("Boo!"); }
  catch ( const std::exception &e ) { std::cout << e.what() << std::endl; }
}

为什么编译器不仅将其重写为

Why does the compiler not just rewrite that as

int f()
{
  std::cout << "Boo!" << std::endl;
}


推荐答案


Why do they do that?

因为C ++异常适用于,特殊情况并不重要。

Because C++ exception are for, well, exceptional circumstances and performance under exceptional circumstances doesn't really matter.

C ++异常被设计成考虑到这一点,确保编译器供应商能够在没有异常抛出的常见情况下提供接近最佳的性能, - 在异常抛出异常情况下的可能性能。

C++' exceptions were designed with that in mind, making sure compiler vendors could deliver near-optimal performance in the common case of no exceptions being thrown, at the cost of worse-than-possible performance in the odd case when exceptions are thrown.

从一开始,鼓励用户仅在特殊情况下使用异常,并且鼓励实施者优化无异常情况(析构函数地址必须按顺序存储当异常到来时调用析构函数。)

虽然实现者可以肯定地花费资源,同时优化奇怪的例外情况,大多数用户不会喜欢,因为总是所以更重要的事情需要改进。

From the very beginning users were encouraged to use exceptions only under exceptional circumstances, and implementers were encouraged to optimize the no-exception case (destructor addresses must be stored somewhere in order to call destructors when an exception comes by) at the cost of the exceptional case.
And while implementers could certainly spend resources at also optimizing the odd exceptional case, most users wouldn't like that, since there's always so much more important things that need improvment.

这篇关于C ++异常抛出/捕获优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆