C++ 风格转换对性能的影响? [英] Performance hit from C++ style casts?

查看:29
本文介绍了C++ 风格转换对性能的影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C++ 样式转换的新手,我担心使用 C++ 样式转换会破坏我的应用程序的性能,因为我有一个 我的中断服务例程中的实时关键截止日期.

I am new to C++ style casts and I am worried that using C++ style casts will ruin the performance of my application because I have a real-time-critical deadline in my interrupt-service-routine.

我听说有些演员甚至会抛出异常!

I heard that some casts will even throw exceptions!

我想使用 C++ 风格的强制转换,因为它会使我的代码更加健壮".但是,如果有任何性能损失,那么我可能不会使用 C++ 风格的强制转换,而是花更多的时间测试使用 C 风格的强制转换的代码.

I would like to use the C++ style casts because it would make my code more "robust". However, if there is any performance hit then I will probably not use C++ style casts and will instead spend more time testing the code that uses C-style casts.

有没有人做过任何严格的测试/分析来比较 C++ 风格转换和 C 风格转换的性能?

Has anyone done any rigorous testing/profiling to compare the performance of C++ style casts to C style casts?

你的结果如何?

你得出了什么结论?

推荐答案

如果 C++ 风格的强制转换可以在概念上被 C 风格的强制转换替换,那么就不会有开销.如果不能,如 dynamic_cast 的情况,没有 C 等效项,您必须以某种方式支付成本.

If the C++ style cast can be conceptualy replaced by a C-style cast there will be no overhead. If it can't, as in the case of dynamic_cast, for which there is no C equivalent, you have to pay the cost one way or another.

以如下代码为例:

int x;
float f = 123.456;

x = (int) f;
x = static_cast<int>(f);

使用 VC++ 为两个强制转换生成相同的代码 - 代码是:

generates identical code for both casts with VC++ - code is:

00401041   fld         dword ptr [ebp-8]
00401044   call        __ftol (0040110c)
00401049   mov         dword ptr [ebp-4],eax

在转换为引用时,唯一可以抛出的 C++ 转换是 dynamic_cast.为避免这种情况,请转换为指针,如果转换失败,它将返回 0.

The only C++ cast that can throw is dynamic_cast when casting to a reference. To avoid this, cast to a pointer, which will return 0 if the cast fails.

这篇关于C++ 风格转换对性能的影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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