Reading notes effective C + + Item 30 understanding inline inside and out (master Admission)

Source: Internet
Author: User
Tags class definition function definition

Recent Beijing house prices rub sharply, bought the people elated, did not buy people gripped, gnashing of teeth, landlord as the North Drift no room a family, really Alexander Big one, These nights sleep is always difficult to sleep, even if sleep, is also floating dream, even if alexander, the enthusiasm and pursuit of C + + is not reduced, Should be touched by the Zhou gong, dream from here to start, the master admission to give me comfort ...

11 points lying in bed, the brain summed up the recent work: the recent development with the inline function is more, it is known that the use of inline is to improve the performance of the program, but the results are not always satisfactory, this catch the urgency ah, eh? How suddenly to the foot of the mountain, surrounded by trees, lush, birds euphemism, flowers blooming, Good comfortable ah, to the distant look, Aoyama Shing, a stone gate at the foot of the mountain, suddenly found sitting next to a white man, like in the practice of taiji, approached a look, how is blue eyes, yellow hair, and then a gaze, I am. This is not the legendary Scot master? I hurried forward, in my own crappy English greeting:

Me: Hello,are you Scott Meyers?

Master: yes, hate Takaboshi know you, I know you, you are in the blog park and my book re-translated again, you are harlanc. Do you have any questions to ask me?

Me: (psychological Chicken Frozen intolerable, Scott unexpectedly can Chinese) Y. Yes (don't stutter), I have one question .....

Master: You should use Chinese.

Me: well, The recent use of inline more, but the efficiency is always unsatisfactory, you say the use of inline good or not good.

Master: come with Me.

Opening the gate, a chubby woman stood in the yard, with a table in front of it, two boxes on the table, and letters and punctuation marks on the box. One is: chocolate? , one is : vegetables? the master glanced at me and Paused.

My heart suddenly a bright, immediately reply: master, you mean to let fat woman guess, guess which eat that?

The master stretched out his forefinger, smiled, and said: no.no,no. The Fat woman represents the program, and the food in the box represents the Post-inline function, and you need to decide for yourself whether the function is "chocolate" or "vegetable," and that the chocolate will make the fat Woman's body more bloated, and the vegetable can make the fat woman lose weight.

I asked: "see you are practicing Tai chi, is not the gas function through the box, teach me."

The master looked at me, tied down the horse, and began to have LUCK. It's going to be a success. I thought.

After luck, the master went to the box, grabbed them with his hand, forced a tear, the box opened, The master looked back at me and said:

Do it More.

Self-made a fantasy, and now start to get to the point:

1. Advantages and disadvantages of the inline function

Inline Function--what a wonderful idea! They look like functions, behave like functions, they are always better than macros (Item 2), you can call them without introducing the overhead of function calls, behave so, what do you want?

You're actually getting more than you think, because the overhead of avoiding function calls is just part of the Story. Compiler optimizations are designed to condense code without function calls, so when you inline a function, you might have the compiler perform optimizations on the function body under a specific scenario. Most compilers do not perform such optimizations on outlined function calls.

But programming is like life, there is no 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 you can see this seems to increase the size of your target Code. On machines with limited memory, excessive inlining can cause too much space to be occupied. Even with virtual memory, the bloat caused by inline code can result in additional paging, reduced instruction cache hit ratios, and consequent performance losses.

On the other hand, if the inline function body is very short, the code generated by the function body itself may be smaller than the code generated by the function Call. If this is the case, the inlining function makes the target code smaller and the instruction cache hit ratio higher!

2. Display and implicit implementation of the inline function

It is important to note that inline is a request to the compiler, not a command. The request can be displayed or implicitly Presented. An implicit method is to define a function within the class Definition:

1 classperson {2  public:3 ...4 intAge ()Const{returntheage; }//an Implicit-inline request:age is5...//defined in a class definition6 Private:7 inttheage;8};

Such a function is usually a member function, but the "friend" function in item 46 can also be defined in the class. If so, they will also be implicitly declared INLINE.

The method of declaring an inline function is displayed by adding the keyword inline before the function Definition. For example, Here's how the standard max template is implemented:

1 // an Explicit inline 2 Const t& Std::max (constconst//  request:std::maxis3return // preceded by "inline"

3. Does the function template have to be inline?

The fact that Max is implemented as a template function reminds us that inline functions and templates need to be defined in the header File. therefore, some of the procedures to the conclusion function template must be INLINE. This conclusion is not valid and may have potential harm, let us analyze and analyze it.

The inline function must be defined in the header file, because most compilation environments perform inline functions at compile Time. In order to replace a function call with a function body, The compiler must understand what the function looks like. (some compilation environments can perform inline at link time, and even some can be inline at run time, such as a managed environment based on The. NET cli), an environment that is an exception, but not a general rule. Inline is a compile-time activity in most C + + Programs. )

The template is also defined in the header file, because the compiler needs to know what the template looks like in order to instantiate it. (there are exceptions to this case, and some compilation environments perform template instantiation during linking.) however, Compile-time Instantiation is the most Common. )

Template instantiation and inline are independent of each other. If you implement a function template and all of the functions that need to instantiate it are inline, declare it as Inline. This is how the Std::max is Implemented. But if you implement a function as a template, and this function does not require inline, then avoid declaring the template inline (whether it is displayed or implicit). There is a price to use inline, and do not use inline until you have considered it. We've already mentioned how inline leads to code bloat (the template author describes a particularly important point of note in Item 44), but there are other costs that we'll discuss in a Minute.

4. In-depth understanding of inline

Before we discuss this, let us understand the fact that inline is just a request to the compiler, and the compiler might ignore it. It is not surprising that most compilers refuse to inline (for example, a function that contains loops or ITERATIONS) for functions that appear to be particularly complex, and that require a function that calls virtual functions and cannot be inline. Virtual means "only at runtime to decide which function to invoke," and inline means "replace with the body of the function at the point of the call before executing the program." If the compiler doesn't know which function will be called, you can't blame it for rejecting the Function's Body.

Let's summarize: whether a function defined as inline is actually being inline depends on the build environment You're Using--and The compiler is primarily a compiler. fortunately, The compiler will diagnose the process, and if the inline function fails, It will issue a warning (Item 53).

Sometimes even if the compiler desperately wants to inline the function, they will generate a separate function body for it. For example, If your program needs to know the address of an inline function, the compiler must generate a outline function body for it. They can't use a function pointer that doesn't exist? Add the fact that the compiler does not inline a function call with a function pointer, which means that the call to the inline function may or may not be inline, depending on how the function call is Made:

1InlinevoidF () {...}//assume compilers is willing to the inline calls to F2 3 void(*pf) () = f;//pf points to F4 5 ...6F ();//This call would be inlined, because it's a "normal" call7 8PF ();//This call probably won ' t be, because it ' s through9 //a function pointer

An inline function that is not inline will linger around you like a ghost, even if you never use a function pointer, because a function pointer is not required by the Programmer. Sometimes the compiler also generates a copy of the Out-of-line function body for constructors and destructors, because objects in an array are constructed and refactored with pointers to Them.

5. Constructors and destructors should not be inline?

In fact, constructors and destructors are usually the slot candidates for the inline function, rather than the constructor of the class derived class, as the surface looks like:

1 classBase {2  public:3 ...4 Private:5 6std::stringbm1, bm2;//Base members 1 and 27 8 }; 9 Ten classDerived: publicBase { one  a  public:                                     -  -Derived () {}//Derived ' s ctor is empty-or it? the  - ...                                             -  - Private:                                   +  -   +  astd::stringdm1, dm2, dm3;//Derived members 1–3 at  -};

This constructor looks like an excellent candidate for the inline function because it does not contain any Code. But don't be blinded by appearances.

C + + must ensure that something happens when an object is created or Refactored. For example, when you use new, your dynamically created objects are automatically initialized by their constructors, and when you use delete, the corresponding destructor is Triggered. When you create an object, the base class part of the object and each of its data members are automatically constructed, and the reverse process, which occurs when the object is destroyed, is the automatic Destructor. If an exception is thrown during construction or destruction, any part of the object that has been constructed should be automatically Freed. In all of these scenarios, C + + points out what must happen, but does not explain how it happens. That's What compiler implementations do, but it's clear that these things don't happen on their own. You have to write some code in your program to make these things happen, which will definitely be inserted into some parts of your code during the compilation Process. Sometimes at the end of constructors and destructors, we can imagine what an empty derived constructor would actually look like:

1Derived::D erived ()//Conceptual Implementation of2{//"empty" Derived ctor3 4Base::base ();//Initialize Base part5 6 Try{dm1.std::string::string(); }//try to construct DM17 8 9 Catch(...) {//if it throws,TenBase::~base ();//destroy base class part and one Throw;//propagate the exception a } - Try{dm2.std::string::string(); }//try to construct dm2 - Catch(...) {//if it throws, thedm1.std::string::~string();//Destroy dm1, -Base::~base ();//destroy base class part, and -  - Throw;//propagate the exception +  - }                              +  a  at Try{dm3.std::string::string(); }//construct DM3 - Catch(...) {//if it throws, -dm2.std::string::~string();//Destroy dm2, -dm1.std::string::~string();//Destroy dm1, -Base::~base ();//destroy base class part, and - Throw;//propagate the exception in } -}

This does not necessarily mean that the compiler will do this because the compiler handles exceptions in a more complex way. But this precisely reflects what the empty constructor of derived must Provide. Regardless of how complex the Compiler's implementation of exception handling is, the derived constructor must call constructors for its data members and base classes, which can affect the attractiveness of the inline, which may themselves be inline.

The same reason applies to the base class constructor, so if it is inline, the code inside it is also inserted into the derived constructor (the derived constructor calls the basic class Constructor.) )。 And if the string constructor is also inline, the derived constructor adds 5 copies of the function code (corresponding to 5 strings in derived). Now you should understand why inline with the derived constructor is a mindless Decision. The same considerations apply to the derived destructor, and we must see that the object initialized by the derived constructor is properly destroyed.

6. Impact of inline on customers

The library designer must estimate the effect of declaring the function as inline, because it is not possible to provide binary updates (binary upgrade) for a client-visible inline function in one library. In other words, if f is an inline function in a library, the client of this library compiles the body of the F function into its own application. If the Library's implementation later decides to modify f, all customers using F must recompile. This is not a popular practice. On the other hand, if f is not an inline function, the modification of F only needs to be re-linked. This is actually less burdensome than recompiling, and if the library that contains the function is dynamically linked, the updated version will be absorbed by the customer unknowingly.

7. Effect of inline on the debugger (debugger)

In order to better develop the program, the above considerations are recorded in the mind, but in the coding process from a practical point of view, One fact dominates all other problems: most debuggers are not well applied to the inline Function. This should not be an unexpected thing. How can you set breakpoints in a function that doesn't have one there? Although some compilation environments support debugging of inline functions, Many compilation environments prohibit inline only when the debug version is Generated.

8. Summary

Deciding which functions should be declared as inline should not be a logical policy Issue. first, do not inline anything, or restrict inline to only those functions that must be inline (Item 46) or very small. By using inline with caution, you can use your debugger very well, but doing so also puts the inline in the right place: as a manual optimization Method. Don't forget the 80-20 rule, which means that a particular 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 the 20% code and optimizing it will improve the performance of the program as a Whole. You can either inline the function or remove the inline until the performance meets the requirements, which, of course, requires you to work on that 20% function, or waste your energy.

What you need to remember:

      • Limit inline to the smallest, most frequently called Function. This makes debugging, binary upgrades easier, and minimizes potential code bloat problems, maximizing the likelihood of a program running Faster.
      • Do not declare a function template as an inline function simply because it appears in the header File.

Reading notes effective C + + Item 30 understanding inline inside and out (master Admission)

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.