C + + keyword inline details _c language

Source: Internet
Author: User
Tags class definition function definition

1. Inline function

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

Copy Code code as follows:

int max (int a, int b)
{
Return a > B? A:B;
}

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

① It is much easier to read and understand the call of the function max than to read an equivalent conditional expression and explain its meaning.

② If you need to make any changes, it's much easier to modify the function than to find and modify each equivalent expression.

③ use functions to ensure uniform behavior, and each test ensures that the same method is implemented

④ functions can be reused without rewriting code for other applications

While there are so many benefits, there is a potential downside to writing a function: Calling a function is much slower than solving an equivalent expression. On most machines, the calling function does a lot of work: Save the Register before the call, restore it on return, copy the arguments, and the program must also move to a new location to execute

Inline functions are supported in C + + to improve the execution efficiency of functions, by using the keyword inline in the function definition (note that the definition is defined rather than the declaration, as described below), the function can be specified as an inline function, and the inline function usually expands it "inline" on each call point in the program, Suppose we define max as an inline function:

Copy Code code as follows:

inline int max (int a, int b)
{
Return a > B? A:B;
}

Then call: Cout<<max (A, b) <<endl;


Expand at compile time: cout<< (a > B a:b) <<endl;

Eliminates the extra overhead of writing Max as a function

2. inline functions and macros

Whether it is "effective C + +" in the "prefer Consts,enums,and inlines to #defines" terms, or "high-quality Programming Guide--C++/C Language" in the "use of functions in conjunction with the substitution of macros", the macro in C + + is basically a waste of , as explained in the book "High Quality Programming Guide--C++/C language":

3. Put inline function into header file

Keyword inline must be placed with the function definition body in order for the function to be inline, and it will have no effect but to place the inline in front of the function declaration.

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

Copy Code code as follows:

inline void Foo (int x, int y); Inline only with function declarations
void Foo (int x, int y)
{
...
}

And the following style of function Foo becomes an inline function:

Copy Code code as follows:

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

So the C + + inline function is a "keyword for implementation", not a "keyword for declaration". Generally, users can read the declaration of a function, but do not see the definition of the function. Although the inline keyword is added to the declaration and definition of the inline function in most textbooks, I don't think inline should appear in the declaration of the function. This detail does not affect function, but it embodies a basic principle of high quality C++/C programming style: Declaration and definition can not be confused, users do not need, and should not know whether the function needs to inline.

The member functions defined in the class declaration will automatically become inline functions, for example:

Copy Code code as follows:

Class A
{
Public
void Foo (int x, int y) {...} Automatically become inline functions
}

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

Inline functions should be defined in the header file, unlike other functions. The compiler must be able to find the definition of the inline function in order to replace the calling function with the function code when the code for the function is expanded in the call point, and not enough for a function declaration in the header file.

Of course inline function definitions can also be placed in the source file, but at this point only the defined source file can use it, and must copy a definition for each source file (that is, the definitions in each source file must be identical), and of course, even in header files, make a copy of each definition, It's just that the compiler completes this copy for you. But instead of being placed in a source file, placing it in a header file ensures that the calling function is defined the same, and that the function definition can be found at the call point to complete the inline (replace).

But you will be very strange, repeated definition so many times, does not produce link error?

Let's take a look at an example:

A.h:

Copy Code code as follows:

Class A
{
Public
A (int a, int b): A (a), B (b) {}
int Max ();

Private
int A;
int b;
};

A.cpp:

Copy Code code as follows:

#include "A.h"

inline int A::max ()
{
Return a > B? A:B;
}

Main.cpp:

Copy Code code as follows:

#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;
}

All normal compile, 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 __thiscall a::max (void)" (? max@a@ @QAEHXZ) main.obj
The definition of a function cannot be found, so inline functions can be defined more than once in a program, as long as the definition of the inline function appears only once in a source file, and in all source files, the definition must be exactly the same.

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 use of inline

Although inline has its advantages, but also should be careful to use, the following excerpt from the "High-quality Programming Guide--C++/C Language":

The Google C + + coding specification is more specific and detailed:

inline function:

Tip: The function is defined as an inline function only if it is only 10 rows or less.

Definition: When a function is declared as an inline function, the compiler expands its inline, instead of invoking the normal function invocation mechanism.
Advantage: When the function body is relatively small, inline this function can make the target code more efficient. For access functions and other function bodies are relatively short, performance-critical functions, encourage the use of inline.
Disadvantage: Misuse of inline will cause the program to become slower. Inline may increase or subtract the amount of target code, depending on the size of the inline function. Inline very short access functions usually reduce code size, but inline a fairly large function will dramatically increase the size of the code. Modern processors, with better use of instruction caching, tend to perform faster with smaller code.
Conclusion: a more reasonable rule of thumb is not to inline functions that exceed 10 lines. With a cautious approach to destructors, destructors tend to look longer than their surface, because there are suppressed members and base class destructors called!
Another practical rule of thumb: inline functions that contain loops or switch statements often outweigh the gains (unless, in most cases, these loops or switch statements are never executed).
It is important that some functions are not necessarily inline with the compiler even if they are declared inline; For example, virtual functions and recursive functions are not normally inline. In general, recursive functions should not be declared as inline functions. (The expansion of the recursive call stack is not as simple as a loop, such as a recursive layer may be unknown at compile time, and most compilers do not support inline recursive functions). The main reason for the inline of a virtual function is to place its function body within the class definition, for convenience, or to describe its behavior as a document, such as a fine, short access function.

-inl.h file:


TIP: The definition of a complex inline function should be placed in a header file with a suffix named-inl.h.


The definition of an inline function must be placed in a header file in order for the compiler to expand the definition inline at the call point. However, the implementation code should theoretically be placed in the. cc file, and we don't want to have too much implementation code in the. h file unless there is a clear advantage in readability and performance.

If the definition of inline functions is relatively short, the logic is simpler, and the implementation code has no problem in the. h file. For example, the implementation of an access function should naturally be placed within the class definition. For the convenience of the creator and the caller, the more complex inline functions can also be placed in the. h file, and if you think this will make the header file unwieldy, you can extract it into a separate-inl.h. This separates the implementation from the class definition and includes the corresponding-inl.h when needed.

This bibliography: "C + + Primer", "high-quality Programming Guide--C++/C language", Google C + + coding specifications

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.