C++开发系列-内联函数

内联函数

C++使用内联函数来替代宏代码片段。

#include <iostream>
int main(){
    printfA();

    return 0;
}

inline void printfA()
{
    int a = 10;
    cout << "a=" << a << endl;
}

C++编译器会将函数插入在函数调用的地方。因此上面代码在编译后大概等价于

#include <iostream>
int main(){

    {
        int a = 10;
        cout << "a=" << a << endl;
    }

    return 0;
}

inline void printfA()
{
    int a = 10;
    cout << "a=" << a << endl;
}

对于内联函数的几个重要的总结:

  • 内联函数没有普通函数调用时的额外开销(压栈、跳转、返回)
  • 内联函数是对编译器的一种请求,因此编译器可能拒绝这种请求
  • C++编译器能够进行编译的优化,因此一些函数即使没有使用inline声明,也可能被编译器内联编译

猜你喜欢

转载自www.cnblogs.com/CoderHong/p/9118644.html