Reading Notes Objective c ++ Item 30 understand inline in-and-out (Master admission), objective tiveitem

Source: Internet
Author: User

Reading Notes Objective c ++ Item 30 understand inline in-and-out (Master admission), objective tiveitem

Recently, property prices in Beijing have soared. People who have bought a house are excited. People who have not bought a house are excited and gritted. The landlord, as a house owner in Beijing, is indeed Alexander, sleeping these nights is always hard to fall asleep. Even if you fall asleep, it is also a dream. Even if Alexander, his passion and pursuit for C ++ are still not diminished, it should have touched Zhou Gong, the dream started from here, and the master came to comfort me...

I am lying in bed at, and I will summarize my recent work in my mind: Recently I used many inline functions. As we all know, inline is used to improve program performance, but the results are always unsatisfactory, this is urgent, huh? Suddenly at the foot of the hill, there were a lot of trees around it, lush birds, and birds were screaming. The flowers were blooming in full bloom. It was so pleasant to look at the distance that the mountains were shining into the clouds. There was a stone door at the foot of the hill, suddenly I found a white-haired person sitting next to me, as if I was practicing taiji. I took a closer look at my blue eyes and yellow hair .. Isn't that the legendary master Scott? I walked forward and gave my greetings in bad English:

Me: Hello, are you Scott Meyers?

MASTER: Yes. Hate Gao Xing for knowing you. I know you. You re-translated my books in the blog garden. You are HarlanC. Do you have any questions to ask me?

Me: (Psychological cool, Scott can speak Chinese) Y .. yes (don't get together), I have one question .....

MASTER: you can still use Chinese.

Me: Well, I 've been using inline a lot recently, but the efficiency is always unsatisfactory. You can say that using inline is better or not.

MASTER: Come with me.

Open the mountain door, a fat woman stood in the yard. There was a table in front of her. There were two boxes on the table, with words and punctuation marks on them. One is:Chocolate ?,One is: Vegetables?The master gave me a look and tried again.

My heart suddenly brightened and I immediately replied: Master, you mean to let the fat woman guess which one to eat?

The master stretched out his index finger and smiled and said, "No. no, No. fat women represent programs, and the food in the box represents the function behind inline. You need to determine whether this function is "Chocolate" or "Vegetables" by yourself. Chocolate will make fat women more bloated, vegetables can make fat women lose weight.

I asked: Do you want to see if you are practicing taiji? Do you want to see through the box through the gas function? How can you teach me.

The master looked at me and took a horse and started to get lucky. This is something to do. I thought.

After luck, the master moved to the box, grabbed them by hand, tore them by force, and opened the box. The master looked back at me and said:

More operations are required.

 

I masturbate myself, and now I start to get started:

1. Advantages and Disadvantages of inline functions

Inline functions-a wonderful idea! They look like functions and act like functions. They are always much better than macros (Item 2). You can call them without introducing the overhead of function calls, and the behavior is like this, what is Fu's request?

You actually want to get more than you think, because avoiding the overhead of function calls is only part of this story. Compiler optimization is designed to concentrate the code without function calls. Therefore, when you use an inline function, you may have the compiler perform optimization operations in a specific scenario on the function body. Most compilers do not perform such optimization on outlined function calls.

However, programming is like living without free lunch, And the inline function is no exception. The internal mechanism of the Inline function is to replace the function call with the function body. Even if there is no statistical doctorate degree, you can see that this seems to increase the size of your target code. On machines with limited memory, excessive inlining may cause excessive space occupation. Even if the virtual memory is used, the expansion caused by inline code will also lead to additional paging, lower the Instruction Cache hit rate and the resulting performance loss.

On the other hand, if the inline function is very short, the code generated by the function itself may be smaller than the code generated by the function call. In this case, the inlining function makes the target code smaller and the Instruction Cache hit rate higher!

2. Display and implicit implementation of Inline functions

Note that inline is a request to the compiler rather than a command. Requests can be displayed or implicitly submitted. The implicit method defines a function in the class definition:

1 class Person {2 public:3 ...4 int age() const { return theAge; } // an implicit inline request: age is5 ... // defined in a class definition6 private:7 int theAge;8 };

 

Such a function is usually a member function, but Item 46 explains that the friend function can also be defined in the class. If so, they are implicitly declared as inline.

The displayed Method for declaring an inline function is to add the keyword "inline" before the function definition. For example, the following is a standard max template implementation method:

1 template<typename T> // an explicit inline2 inline const T& std::max(const T& a, const T& b) // request: std::max is3 { return a < b ? b : a; } // preceded by “inline”

 

3. Must the function template be inline?

The fact that max is implemented as a template function reminds us that both the inline function and the template need to be defined in the header file. Therefore, some programs need to conclude that the function template must be inline. This conclusion is ineffective and may cause potential harm. Let's analyze it.

The Inline function must be defined in the header file, because most compilation environments execute Inline functions during compilation. To replace a function call with a function body, the compiler must understand what the function looks like. (Some compilation environments can execute inline during linking, or even some can do inline at runtime (such as based on.. net cli), such environments are exceptions, but not general rules. In most C ++ programs, inline is a compile-time activity .)

The template is also defined in the header file, because the compiler needs to know what the template looks like when instantiating it. (This is also an exception. Some compilation environments execute template instantiation during the link. However, instantiation is the most common during compilation .)

Template instantiation and inline are independent of each other. If you implement a function template and all the functions that need to be instantiated by this template are inline, declare it as inline. The above std: max is implemented in this way. However, if you implement a function as a template and this function does not require inline, do not declare the template as inline (whether displayed or implicitly ). There is a price to use inline. Do not use inline before careful consideration. We have mentioned how inline causes code expansion (a particularly important note for the template author in Item 44), but there will be other overhead, which we will discuss later.

4. in-depth understanding of inline

Before we discuss it, let us first understand the fact that inline is only a request to the compiler, And the compiler may ignore it. Most compilers refuse to execute inline (for example, a function that contains loops or iterations) for seemingly complex functions. functions that need to call virtual functions cannot execute inline. Don't be surprised. Virtual means that "You can only decide which function to call at runtime," and inline means "Replace with the function body at the call point before executing the program ". If the compiler does not know which function will be called, you cannot blame it for rejecting inline function bodies.

To sum up, whether a function defined as inline is truly inline depends on the compiling environment you are using. This compiling environment is mainly a compiler. Fortunately, the compiler will diagnose this process. If a function in inline fails, it will issue a warning (Item 53 ).

Sometimes, even if the compiler is eager to inline functions, they will generate a separate function body. For example, if your program needs to know the address of the inline function, the compiler must generate an outline function body. They cannot use a non-existent function pointer, right? Add the following fact: the compiler does not perform inline for the function when using the function pointer, which means that the call to the inline function may be inline or not, depends on how the function is called:

1 inline void f() {...}       // assume compilers are willing to inline calls to f2 3 void (*pf )() = f;          // pf points to f4 5 ...6 f();                   // this call will be inlined, because it’s a “normal” call7 8 pf(); // this call probably won’t be, because it’s through9 // a function pointer

Inline functions without inline will be around you like a ghost, even if you have never used function pointers, because not only programmers need function pointers. Sometimes the compiler will generate an out-of-line function body for the constructor and destructor, because the pointer to the objects in the array must be used for construction and analysis.

 

5. Shouldn't constructor and destructor be inline?

In fact, constructor and destructor are usually candidates for inline functions, rather than the constructor of the Derived class:

 1 class Base { 2 public: 3 ... 4 private: 5  6 std::string bm1, bm2;              // base members 1 and 2 7  8 };                                             9 10 class Derived: public Base {    11 12 public:                                    13 14 Derived() {}                             // Derived’s ctor is empty — or is it?15 16 ...                                            17 18 private:                                  19 20  21 22 std::string dm1, dm2, dm3;    // derived members 1–323 24 };       

This constructor looks like an outstanding candidate for the inline function because it does not contain any code. But do not be blinded by superficial phenomena.

 

When an object is created or destructed, C ++ must ensure the occurrence of some things. For example, when you use new, your dynamically created objects are automatically initialized by their constructors. When you use delete, the corresponding destructor will be triggered. When you create an object, the base class part of the object and each of its data members will be automatically built. When the object is destroyed, the opposite process is the automatic structure. If an exception is thrown during construction or analysis, any part of the constructed object should be automatically released. In all these scenarios, c ++ points out what must happen, but does not explain how to happen. This is what the compiler implementer has to do, but it should be clear that these tasks will not happen on their own. You must write some code in your program to make these things happen. These will be inserted to some part of your code during compilation. Sometimes at the end of the constructor and destructor, we can imagine what an empty Derived constructor actually looks like:

 1 Derived::Derived() // conceptual implementation of 2 { // “empty” Derived ctor 3  4 Base::Base();                       // initialize Base part 5  6 try { dm1.std::string::string(); }          // try to construct dm1 7  8  9 catch (...) { // if it throws,10 Base::~Base(); // destroy base class part and11 throw; // propagate the exception12 }13 try { dm2.std::string::string(); } // try to construct dm214 catch(...) { // if it throws,15 dm1.std::string::~string(); // destroy dm1,16 Base::~Base(); // destroy base class part, and17 18 throw;                     // propagate the exception19 20 }                             21 22 23 try { dm3.std::string::string(); } // construct dm324 catch(...) { // if it throws,25 dm2.std::string::~string(); // destroy dm2,26 dm1.std::string::~string(); // destroy dm1,27 Base::~Base(); // destroy base class part, and28 throw; // propagate the exception29 }30 }

 

This write does not mean that the compiler will certainly do this, because the way the compiler handles exceptions is more complicated. However, this accurately reflects what the Derived empty constructor must provide. No matter how complicated the compiler implements exception handling, the Derived constructor must call constructor for its data members and base classes. These calls (maybe they are inline) will affect the attractiveness of inline.

 

The same reason applies to the base class constructor, so if it is inline, the code in it will also be inserted into the Derived Constructor (the Derived constructor will call the base class constructor .). If the string constructor is also replaced by inline, the Derived constructor adds five copies of Function Code (corresponding to five strings in Derived ), now you should understand why inline is an brainless decision on the Derived constructor. The same considerations apply to the Derived destructor. We must see that the object initialized by the Derived constructor is destroyed properly.

 

6. Impact of Inline on customers

 

The library designer must estimate the impact of declaring a function as inline, because it is impossible to provide binary Update (binary upgrade) for the inline function visible to the customer in a library. In other words, if f is an inline function in a library, the database's customers compile the f function body into their own applications. If the database implementer decides to modify f later, all customers who use f must re-compile. This is an undesirable practice. On the other hand, if f is not an inline function, you only need to relink the modification to f. This actually reduces the workload due to new compilation. If the library containing this function is dynamically linked, the updated version will be unconsciously absorbed by the customer.

 

7. Impact of Inline on the debugger

 

In order to better develop programs, we keep the above considerations in mind, but in the coding process, from a practical point of view, one fact prevails over all other problems: most debuggers cannot be well applied to inline functions. This should not be unexpected. How can you set a breakpoint in a function that does not exist? Although some compilation environments support debugging of inline functions, many compilation environments only disable inline when generating debugging versions.

 

8. Summary

Deciding which functions should be declared as inline should not be a logical policy issue. First, do not use inline anything, or only restrict inline to functions that must be inline (Item 46) or small functions. By using inline with caution, you can use your debugger well, but in this way, you also place inline in the appropriate position: as a method for manual optimization. Do not forget the 80-20 rule, which means that a specific program will use 80% of the time to execute 20% of the Code. This is an important rule, because it reminds you that as a software engineer, identifying and optimizing the 20% code will improve the overall performance of the program. You can perform inline on your function or remove the inline until the performance meets the requirements. Of course, this requires your efforts on the 20% function. Otherwise, it is a waste of energy.

 

What you need to remember:

    • Limit inline to the smallest and most frequently called function. This will make debugging and binary upgrade easier, minimize potential code expansion problems, and increase the possibility of program running speed.
    • Do not declare the function template as an inline function just because it appears in the header file.

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.