为什么我应该使用内联代码? [英] Why should I ever use inline code?

查看:133
本文介绍了为什么我应该使用内联代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




  • 我是一个C / C ++开发人员,这是一个很大的问题。 常规代码和内联代码之间的区别?

  • 这是什么主要区别?

  • 内联代码只是宏的形式 / li>
  • 在选择嵌入您的代码时,必须做什么样的折衷?



p>

解决方案



  • 常规代码和内联代码之间有很大的区别?


是和否。不,因为内联函数或方法具有与常规函数完全相同的特性,最重要的是它们都是类型安全的。是的,因为编译器生成的汇编代码会有所不同;使用常规函数,每个调用将被转换成几个步骤:在栈上推送参数,使得跳转到函数,弹出参数等,而对内联函数的调用将由其实际代码替换,如a



  • 内联代码只是宏的形式?


!宏是简单的文本替换,可能导致严重的错误。考虑以下代码:

  #define unsafe(i)(i)> = 0?(i): - i))

[...]
unsafe(x ++); // x递增两次!
unsafe(f()); // f()被调用两次!
[...]

使用内联函数,在实际执行该函数之前进行评估。



  • 什么样的折衷

通常情况下,程序执行应该更快,当使用内联函数,但使用更大的二进制代码。有关详情,请阅读 GoTW#33


I'm a C/C++ developer, and here are a couple of questions that always baffled me.

  • Is there a big difference between "regular" code and inline code?
  • Which is the main difference?
  • Is inline code simply a "form" of macros?
  • What kind of tradeoff must be done when choosing to inline your code?

Thanks

解决方案

  • Is there a big difference between "regular" code and inline code?

Yes and no. No, because an inline function or method has exactly the same characteristics as a regular one, most important one being that they are both type safe. And yes, because the assembly code generated by the compiler will be different; with a regular function, each call will be translated into several steps: pushing parameters on the stack, making the jump to the function, popping the parameters, etc, whereas a call to an inline function will be replaced by its actual code, like a macro.

  • Is inline code simply a "form" of macros?

No! A macro is simple text replacement, which can lead to severe errors. Consider the following code:

#define unsafe(i) ( (i) >= 0 ? (i) : -(i) )

[...]
unsafe(x++); // x is incremented twice!
unsafe(f()); // f() is called twice!
[...]

Using an inline function, you're sure that parameters will be evaluated before the function is actually performed. They will also be type checked, and eventually converted to match the formal parameters types.

  • What kind of tradeoff must be done when choosing to inline your code?

Normally, program execution should be faster when using inline functions, but with a bigger binary code. For more information, you should read GoTW#33.

这篇关于为什么我应该使用内联代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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