c++的内联函数

一、内联函数的利弊
利:
1、不需要蒙受函数调用所带来的额外开销。
2、编译器最优化机制通常被设计用来浓缩那些“不含函数调用”的代码,当inline某个函数时,编译器就可以对它执行语境相关最优化。
弊:
1、inline函数的整体观念是,将“对函数的每一次调用”都以函数本体替换之,这样会增加目标码大小。
2、inline造成的代码膨胀会导致额外的换页行为,降低指令高速缓存装置的命中率,以及伴随这些而来的效率损失。
折中:
对函数本体较小的函数使用inline,编译器针对“函数本体”所产出的码可能比针对函数调用所产出的码更小,这样就可以实现较小的目标码和较高的指令高速缓存装置命中率。
二、内联函数使用
inline只是对编译器的一个申请,不是强制命令。这项申请可以隐喻提出,也可以明确提出。

    //隐喻声明:
    class dog{
         public:
              ...
              int age() const {return theAge;}
              ...
          private:
              int theAge;
    };
    //明确声明:
    //在函数定义前加上关键字inline。
    //示例1、
    inline.cpp
    #inclue 
    //an inline function definition
    inline double square(double x) {return x * x;}
    int main()
     {
          return 0;
     }
    //示例2、
    //标准的max template(来自)
    template
    inline const T& std::max(const T& a, const T& b)
    {return a < b ? b : a;}

三、内联函数不内联
内联函数不内联,简单解释就是程序员请求将函数作为内联函数时,编译器并不一定会满足这种情况。
1、最简单的一种情况:编译认为该函数过大或注意到函数中有递归或循环。
2、virtual函数也会使inline落空,因为virtual意味着等待,直到运行期才确定调用哪个函数。
3、编译器通常不对“通过函数指针而进行的调用”实施inlining。

例:
inline void f() { ...}         //假设编译器有意inline“对f的调用”
void (* pf) () = f ;           //pf指向f
f();                           //这个调用将被inlined,因为它是一个正常调用
pf();                          //这个调用或许不被inlined,因为它通过函数指针达成

四、内联与宏(c++ primer plus)
The inline facility is an addition to C++. C uses the preprocessor #define statement to provide
macros, which are crude implementations of inline code. For example, here’s a macro for squaring a
number:
#define SQUARE(X) XX
This works not by passing arguments but through text substitution, with the X acting as a symbolic
label for the “argument”:
a = SQUARE(5.0); is replaced by a = 5.0
5.0;
b = SQUARE(4.5 + 7.5); is replaced by b = 4.5 + 7.5 * 4.5 + 7.5;
d = SQUARE(c++); is replaced by d = c++c++;
Only the first example here works properly. You can improve matters with a liberal application of
parentheses:
#define SQUARE(X) ((X)
(X))
Still, the problem remains that macros don’t pass by value. Even with this new definition,
SQUARE(c++) increments c twice, but the inline square() function in Listing 8.1 evaluates c , passes
that value to be squared, and then increments c once.
The intent here is not to show you how to write C macros. Rather, it is to suggest that if you have
been using C macros to perform function-like services, you should consider converting them to C++
inline functions.

你可能感兴趣的:(c/c++编程)