The C++ keyword inline is described in detail

  • 2020-04-02 02:08:40
  • OfStack

1.   Inline function

In C++, we usually define the following function to find the maximum value of two integers:


int max(int a, int b)
{
 return a > b ? a : b;
}

The advantages of defining a function for such a small operation are:

It is much easier to read and understand the call to function Max than to read an equivalent conditional expression and explain its meaning

If you need to make any changes, it is much easier to modify the function than to find and modify the equivalent expression everywhere

Using functions ensures uniform behavior, with each test guaranteed to be implemented in the same way

Functions can be reused without having to rewrite code for other applications

For all the benefits, there is a potential drawback to writing functions: calling functions is much slower than solving equivalent expressions. On most machines, calling a function does a lot of work: registers are saved before the call and restored on return, arguments are copied, and the program must be executed in a new location

C + + supports inline functions, its purpose is to improve the efficiency of execution of the function, the inline with keywords in a function definition (note is to define the rather than the statement below to continue to talk about) in the front of the function can be specified as an inline function, inline function is usually put it on each call point in the program "inline", suppose we defined Max inline function:


inline int max(int a, int b)
{
 return a > b ? a : b;
}

Then call: cout < < Max (a, b) < < Endl;


At compile time, expand to: cout < < (a > B? A: b) < < Endl;

This eliminates the extra execution overhead of writing Max as a function

2.   Inline functions and macros

Whether it's the clause "Prefer consts, enums, and inlines to #defines" in Effective C++, or "replace macros with function inlining" in the guide to high-quality programming C++/C, macros are basically obsolete in C++, as explained in the book guide to high-quality programming C++/C:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201401/2014126161246983.jpg" >

3.   Put the inline function into the header file

The keyword inline must be placed with the body of the function definition to make the function inline. Simply placing inline before the function declaration does not work.

The following style of function Foo cannot be inline:


inline void Foo(int x, int y);   //Inline is only placed with the function declaration & handed; & have spent
void Foo(int x, int y)
{
 ...
} 

The following style of function Foo becomes inline:


void Foo(int x, int y);   
inline void Foo(int x, int y)   //Inline is placed with the body of the function definition
{
 ...
} 

So the C++ inline function is a "keyword for implementation", not a "keyword for declaration". In general, the user can read the declaration of the function, but cannot see the definition of the function. Although the inline keyword appears before the declaration and definition body of inline functions in most textbooks, I don't think inline should appear in the declaration of functions. This detail, while not affecting the functionality of the function, embodies a fundamental principle of the high quality C++/C programming style: declarations and definitions are not to be confused, and users do not need or should not know whether functions need to be inline.

A member function defined in a class declaration automatically becomes an inline function, for example:


class A
{  
public:
 void Foo(int x, int y) { ... }   //Automatically becomes an inline function & PI;
} 

But whether the compiler actually inlines it depends on how the Foo function is defined

Inline functions should be defined in a header file, unlike other functions. The compiler must be able to find the definition of the inline function to replace the calling function with the function code when it calls the inline expanded function's code, and it is not enough to just declare the function in the header file.

Inline function definitions, of course, can also be placed in the source file, but now only the definition of the source file can use it, and must be a definition for each source file copy (that is, the definition of each source file must be exactly the same), even in a header file, of course, is to do a copy each definition, is just the compiler to complete this copy for you. But instead of putting it in the source file, putting it in the header file ensures that the calling function is defined in the same way and that the function definition can be found at the calling point to complete the inlining (substitution).

But you'd be surprised if you repeated the definition so many times that you wouldn't get a link error, right?

Let's take a look at an example:

A.h:


class A
{
public:
 A(int a, int b) : a(a),b(b){}
 int max();
private:
 int a;
 int b;
};

A.c pp:


#include "A.h"
inline int A::max()
{
 return a > b ? a : b;
}

The Main. CPP:


#include <iostream>
#include "A.h"
using namespace std;
inline int A::max()
{
 return a > b ? a : b;
}
int main()
{
 A a(3, 5);
 cout<<a.max()<<endl;
 return 0;
}

Everything compiles normally, output result: 5

 


If you do not define the Max inline function in main.cpp, a link error occurs:

Error LNK2001: unresolved external symbol "public: int/scall A:: Max (void)" (? Max @ A @ @ QAEHXZ). The main obj
The definition of the function cannot be found, so inline functions can be defined more than once in the program, as long as the definition of the inline function appears only once in a source file and must be exactly the same in the source file.

When you add or modify the inline function in a header file, all source files that use the header file must be recompiled.

4.   Careful with inline

Inline has its benefits, but it should be used with caution. The following is an excerpt from the guide to high-quality programming C++ / C:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201401/2014126161607971.jpg" >

Google C++ code specification is more explicit and detailed:

Inline function:

Tip: only define a function as inline if it has 10 lines or less.

Definition: when a function is declared inline, the compiler expands it inline instead of calling it the usual way.
Advantages: inlining makes object code more efficient when the function body is small. Inlining is encouraged for access functions and other functions with short, performance-critical bodies.
Disadvantages: inline abuse will cause the program slow. Inline may make the target code quantity or increase or decrease, depending on the size of the inline function. Inline very short access function will usually reduce the code size, but a considerable functions inline will dramatically increase the code size. Modern processor due to better use of the instruction cache, compact code often perform faster.
Conclusion: a reasonable rule of thumb is not to inline functions more than 10 lines. Beware of destructors, which tend to be longer than they appear because there are implicit member and base class destructors being called!
Another practical rule of thumb: inlining functions that contain loops or switch statements is often more than it pays to do so (except in most cases where these loops or switch statements are never executed).
It is important that some functions not be inlined by the compiler even if they are declared inline; Such as virtual function and recursive function will not be normal inline. Usually, recursive functions should not be declared as an inline function. (recursive call stack of expansion is not as easy as circulation, such as recursive layer may be unknown at compile time, most of the compiler does not support inline recursive function). The virtual function inlining a function of the main reason is want to have it put inside the class definition, in order to figure a convenient, describe its behavior or as a document, such as short fine access function.

- inl. H file:


Tip: the definition of a complex inline function should be placed in a header file with the suffix -inl.h.


The definition of the inline function must be in the header file before the compiler can expand the definition inline at the call point.

If the inline function definitions are short, logic is simple, the implementation code on. H file without any problem. For example, the realization of access function for granted should be put inside the class definition. Out of the writers and the caller is convenient, more complex inline function can also be in the h file, if you think this will make the header file appears bulky, can also extract it to a separate - inl. H. Such separation, the implementation and the class definition when need to contain the corresponding - inl. H.

Bibliography: C++ Primer, high quality programming guide - C++ / C language, Google C++ coding specification


Related articles: