当前位置 博文首页 > C++内联函数

    C++内联函数

    作者:Thrush 时间:2021-01-16 16:05

    C++对代码有许多优化的地方,从某种程度上来看,内联函数就是一种优化,看一下C++官方标准对inline的描述:
    When the compiler inline-expands a function call, the function’s code gets inserted into the caller’s code stream (conceptually similar to what happens with a #define macro). This can, depending on a zillion other things, improve performance, because the optimizer can procedurally integrate the called code — optimize the called code into the caller.
    There are several ways to designate that a function is inline, some of which involve the inline keyword, others do not. No matter how you designate a function as inline, it is a request that the compiler is allowed to ignore: the compiler might inline-expand some, all, or none of the places where you call a function designated as inline. (Don’t get discouraged if that seems hopelessly vague. The flexibility of the above is actually a huge advantage: it lets the compiler treat large functions differently from small ones, plus it lets the compiler generate code that is easy to debug if you select the right compiler options.)

    大致的意思就是:
    当编译器内联扩展函数调用时,该函数的代码将插入到调用者的代码流中(概念上与#define宏类似)。 取决于不计其数的其他方面,这可以提高性能,因为优化器可以在过程上集成被调用的代码—将被调用的代码优化到调用程序中。
    有几种方法可以指定一个函数为内联,其中一些涉及inline关键字,而其他则不涉及。 无论您如何将函数指定为内联函数,都要求编译器忽略该请求:编译器可能会内联扩展您调用被指定为内联函数的位置的部分,全部或全部。 (不要灰心,因为这似乎望尘莫及。上面的灵活性实际上是一个巨大的优势:它可以使编译器将大型函数与小型函数区别对待,另外,如果选择了,编译器可以生成易于调试的代码。 正确的编译器选项。)
    通俗的来讲就是将函数的调用直接转为编程语句来执行,从而减少栈的操作。
    来看下面的代码:

    inline int function(int a ,int b ){
    return a + b;
    }
    int main(){
    cout<<function(10,20)<<endl;
    }
    

    该程序执行时直接通过优化可近似看做:

    inline int function(int a ,int b ){
    return a + b;
    }
    int main(){
    cout<<10 + 20<<endl;
    }
    

    内联函数会提高性能吗?
    没有简单的答案。内联函数可能会使代码变快,但可能会使代码变慢。它们可能使可执行文件变大,可能使可执行文件变小。它们可能会引起颠簸,它们可能会阻止颠簸。它们可能而且通常与速度完全无关。

    原文摘自C++官方
    以上个人理解内容如有错误,还请指点纠正