C++:inline

inline

inlineC ++ is a key provided, before it is used to define the function representing the function is defined as inline functions . Meaning inline function is: function point in calling the function body directly deployed to replace the function call.

inline int getZero() {
    return 0;
}
int a = getZero();

If this function is not defined inline, then the statement a, the program is actually working is the getZero()function onto the stack, perform the function returns a value of 0 and get out of the stack, and finally assigned to 0 a. In defined as inlineafter, the compiler will inline function as a function of the body, that is, in a statement at the point of call awhen deployed directly get the result and assigned to 0 a, eliminating the function call stack and the process stack, improved performance.

So if it is a bit more complex inline function?

inline int get(int a, int b, int c, int x) {
    return (a * x + b) * x +c;
}
int b = get(1, 2, 1, 4);

Compared to before getZero(), get()the function many more operations, it will be expanded to the point of call int b = (1 * 4 + 2) * 4 + 1;. One can imagine that the more difficult the more complex functions in vivo inline expansion.

This also leads to the definition of the characteristics of inline function:

  • inlineKeyword compiler from the recommended action, if the compiler inline determined by the compiler.
  • inlineKeyword appears in the function declaration at does not work, appear in the function definition is valid.
  • The complex logic functions are defined as inline meaningless, such as nested calls, and so on recursively.
  • Classes are defined in the function implicitly inlined , and need to be explicitly defined outside the class add inlinekeywords.
// inline无意义
inline int f1(int x) {
    if (x == 0 || x== 1) return 1;
    return f(x - 1) + f(x - 2);
}

// inline无意义
inline int f2();

class LiF {
public:
    LiF() = default;
    LiF(int _lif);
    void set(int _lif) { lif = _lif; } // 类内隐式内联
    int get();
private:
    int lif;
}

LiF::LiF(int _lif): lif(_lif) {} // 无内联

inline int LiF::get() { return lif; } // 类外显式内联

Since inlining can improve efficiency, why not all functions are defined as inline it? The problem is not difficult to answer. Inline premise that can be deployed at the point of call, it can not expand when apparently complex functions mentioned before; and if the time to perform a particular function inlining consumed much longer than the consumption of calls, then this is inline fail. Furthermore, the efficiency improvement program behind there must be more memory consumption, inline bring efficiency gains by copying the code to call the point of implementation, which obviously increases the amount of code. This then requires the programmer to be used with caution inline.

Guess you like

Origin www.cnblogs.com/Li-F/p/11522172.html