Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

c++ - what is/are the purpose(s) of inline?

I had a discussion with Johannes Schaub regarding the keyword inline. The code there was this:

namespace ... {
    static void someFunction() {
        MYCLASS::GetInstance()->someFunction();
    }
};

He stated that:

Putting this as an inline function may save code size in the executable

But according to my findings here and here it wouldn't be needed, since:

  • [Inline] only occurs if the compiler's cost/benefit analysis show it to be profitable
  • Mainstream C++ compilers like Microsoft Visual C++ and GCC support an option that lets the compilers automatically inline any suitable function, even those not marked as inline functions.

Johannes however states that there are other benefits of explicitly specifying it. Unfortunately I do not understand them. For instance, he stated that And "inline" allows you to define the function multiple times in the program., which I am having a hard time understanding (and finding references to).

So

  1. Is inline just a recommendation for the compiler?
  2. Should it be explicitly stated when you have a small function (I guess 1-4 instructions?)
  3. What other benefits are there with writing inline?
  4. is it needed to state inline in order to reduce the executable file size, even though the compiler (according to wikipedia [I know, bad reference]) should find such functions itself?

Is there anything else I am missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To restate what I said in those little comment boxes. In particular, I was never talking about inlin-ing:

// foo.h:
static void f() {
  // code that can't be inlined
}

// TU1 calls f
// TU2 calls f

Now, both TU1 and TU2 have their own copy of f - the code of f is in the executable two times.

// foo.h:
inline void f() {
  // code that can't be inlined
}

// TU1 calls f
// TU2 calls f

Both TUs will emit specially marked versions of f that are effectively merged by the linker by discarding all but one of them. The code of f only exists one time in the executable.

Thus we have saved space in the executable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...