我已经读到使用 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++ 异常来构建一个案例来支持或反对 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?
在 some 平台和 some 编译器上进行异常处理是有成本的.
There is a cost associated with exception handling on some platforms and with some 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
和面向 64 位的 Visual Studio 采用的另一种技术仅在抛出异常时产生开销(该技术涉及遍历调用堆栈和表抬头).在很少抛出异常的情况下,这实际上可以产生更高效的代码,因为不必处理错误代码.
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++ 异常以什么方式减慢代码速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!