Inline usage in C + +

Source: Internet
Author: User

1. Reasons for introducing the inline keyword

In C + +, in order to solve some of the frequently called small functions to consume a lot of stack space (stack memory), especially the introduction of the inline modifier, expressed as an inline function.

stack space refers to the memory space where the program's local data (that is, the data inside the function) is placed.

In the system, the stack space is limited, if the frequent use of a large amount of space will cause the program error, such as the function of the dead loop recursive call the end result is to cause the stack memory space exhaustion.

Let's look at an example:

 #include <stdio.h>//function is defined as inline: inline function inline char* dbtest (int a) {return (i% 2 > 0)?  "odd":  "even";} int Main () {int i = 0; for (I=1; i < 100; i++) {printf (" i:%d parity:%s/n ", I, dbtest (i))}}       

The above example is the use of the standard inline function, the benefits of using inline modification we do not see the surface, in fact, the internal work is in each for loop inside of any call dbtest (i) to replace the place (i%2>0)? " Odd ":" Even ", so that the frequent calls to the function of the stack memory duplication of the cost of opening up.

2. Inline Usage Restrictions

The use of inline is limited , and inline is only suitable for the simple use of the number of the code in the body, not complex structure control statements such as while, switch, and cannot inline the function itself cannot be a direct recursive function (that is, Own functions are also called within themselves).

3. Inline is only a recommendation to the compiler

The inline function is only a recommendation to the compiler , so the final can be really inline, look at the meaning of the compiler, if it thinks that the function is not complex, can be expanded at the call point, it will be really inline, not to say that the inline will be inline, the declaration of inline is only a suggestion.

4. Recommendation: the definition of the inline function is placed in the header file

Second, because the inline function is to be expanded at the point of invocation, the compiler must everywhere define the inline function , otherwise it becomes a call to a non-inline function. Therefore, this requires that each file that invokes the inline function has the definition of the inline function .

Therefore, it is appropriate to place the definition of an inline function in the header file , saving you the hassle of implementing it once for each file.

The declaration is consistent with the definition : If the inline function is implemented once in each file, it is best to ensure that each definition is the same, otherwise it will cause undefined behavior. If not all the definitions in each file are the same, then the compiler expands which one depends on the specific compiler. Therefore, it is best to put the inline function definition in the header file .

5. member functions in classes and inline

A member function defined in a class is inline by default, which is of course best if the function definition is given within the class when the class is defined. If a member function definition is not given in the class and you want to inline the function, then inline is added outside the class, otherwise it is not considered inline.

For example

class A{    public:void Foo(int x, int y) { } // 自动地成为内联函数}

It is not a good programming style to place the definition of a member function in a class declaration, although it can bring about convenience in writing, but it should be changed to the following example:

// 头文件class A{    public:    void Foo(int x, int y);}

// 定义文件inline void A::Foo(int x, int y){} 

6. Inline is a "keyword for implementation"

The keyword inline must be placed with the function definition body in order for the function to be inline, and only the inline is placed before the function declaration.

The following style of function Foo cannot be an inline function:

inline void Foo(int x, int y); // inline 仅与函数声明放在一起void Foo(int x, int y){}

The following style of function foo becomes an inline function:

void Foo(int x, int y);inline void Foo(int x, int y) {} // inline 与函数定义体放在一起

So, inline is a "keyword for implementation ", not a "keyword for declaration." In general, the user can read the declaration of a function, but cannot see the definition of the function. Although the inline keyword is prepended to the declaration and definition of inline functions in most textbooks, I don't think inline should appear in the declaration of a function . While this detail does not affect function functionality, it embodies a fundamental tenet of high quality C++/C program design: declarations and definitions are not to be confused, and the user does not need to know whether the function needs to be inline.

7. Use inline with caution

Inline can improve the efficiency of function execution, why not all functions are defined as inline functions? If all functions are inline functions, is it useful to "inline" the keyword?
Inline is at the expense of code bloat (replication) , which simply eliminates the overhead of function calls and thus increases the efficiency of function execution.
If the time of executing the code in the function body is greater than the cost of the function call, then the efficiency will be harvested very little. On the other hand, the invocation of each inline function is to copy code, which increases the total code size of the program and consumes more memory space.

It is not advisable to use inline in the following situations:
(1) If the code in the function body is longer , using inline will result in a high cost of memory consumption .
(2) If there is a loop in the function body, the time to execute the function body code is greater than the cost of the function call. The constructors and destructors of a class are easily misunderstood to be more efficient for inline use. Be aware that constructors and destructors may hide behaviors such as "secretly" executing constructors and destructors for base or member objects . So don't arbitrarily place the definitions of constructors and destructors in class declarations . A good compiler will automatically cancel the unworthy inline based on the body of the function definition (this further illustrates that inline should not appear in the declaration of the function).

8. Summary

Inline functions are not a panacea for enhanced performance. It can only get the effect we want when the function is very short , but if the function is not very short and is called in many places, it will increase the volume of the executable body.
The most annoying thing is when the compiler refuses to inline. In the old implementation, the results are very unsatisfactory, although in the new implementation of a great improvement, but still not so perfect. Some compilers are smart enough to point out which functions can be inline and which cannot, but most compilers are less intelligent, so this requires our experience to judge. if the inline function does not enhance performance, avoid using it!

Inline usage in C + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.