问题描述
我已经读过,使用C ++异常来处理异常,而不是检查返回值有一些开销。我只是说没有引发异常时产生的开销。我还假设你需要实现代码,实际检查的返回值,并做适当的事情,不管是什么相当于catch块会做。并且,将代码抛出异常对象与45个状态变量内部到代码,为每个错误返回一个负整数也是不公平的。
I have read that there is some overhead to using C++ exceptions for exception handling as opposed to, say, checking return values. I'm only talking about overhead that is incurred when no exception is thrown. I'm also assuming that you would need to implement the code that actually checks the return value and does the appropriate thing, whatever would be the equivalent to what the catch block would have done. And, it's also not fair to compare code that throws exception objects with 45 state variables inside to code that returns a negative integer for every error.
我不是试图构建一个针对或针对C ++异常的情况,仅基于哪个可能执行得更快。我听说有人做最近的情况下,使用例外的代码应该运行与基于返回代码的代码一样快,一旦你考虑到需要检查返回值和处理错误的所有额外的簿记代码。
I'm not trying to build a case for or against C++ exceptions solely based on which one might execute faster. I heard someone make the case recently that code using exceptions ought to run just as fast as code based on return codes, once you take into account all the extra bookkeeping code that would be needed to check the return values and handle the errors. What am I missing?
推荐答案
在某些平台和某些编译器上有与异常处理相关的费用。
There is a cost associated with exception handling on some platforms and with certain compilers.
也就是说,Visual Studio在构建32位目标时,会在每个具有非平凡析构函数的局部变量的函数中注册一个处理程序。基本上,它设置了 try / finally
处理程序。
Namely, Visual Studio, when building a 32-bit target, will register a handler in every function that has local variables with non-trivial destructor. Basically, it sets up a try/finally
handler.
另一种技术,由gcc和Visual Studio 64位,只在引发异常时引发开销(该技术涉及遍历调用堆栈和表查找)。在很少抛出异常的情况下,这实际上可以导致更有效的代码,因为不必处理错误代码。
The other technique, employed by gcc and Visual Studio targeting 64-bits, only incurs overhead when an exception is thrown (the technique involves traversing the call stack and table lookup). In cases where exceptions are rarely thrown, this can actually lead to a more efficient code, as error codes don't have to be processed.
这篇关于当没有异常被抛出时,C ++异常以什么方式减慢代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!