开发者

Is this function guaranteed to be expanded inline

I was going through some code at work and I found this

inline
  FLAGS get_flags(void) {
  FLAGS res;
  memset(&res, 0, sizeof(res));
  return res
}

This is declared in a header file included in the program. I realize it would be a very bad thing if it was not inlined as this i开发者_开发问答s allocated on the stack. We have never had problems with the code in question, but I was just curious about it.


No, it is not guaranteed to be expanded inline. inline is merely a hint to the compiler.

That said, while res does indeed exist on the stack, you return a copy of it. It won't be "a very bad thing" if inline expansion doesn't occur.


No, it is not guaranteed that the compiler will inline it. See this answer.

As Strousoup says in The C++ Programming Language

The inline specifier is a hint to the compiler that it should attempt to generate code [...] inline rather than laying down the code for the function once and then calling through the usual function call mechanism.

Note the key word hint.


inline has two purposes, but only one matters anymore.

As others have said, the purpose of hinting to the compiler that the function should be inlined is all but useless. The compiler is much better at determining what should be inlined than the programmer.

However, the important second use (which applies in your case) is that it breaks the one-definition rule (ODR). That is, under normal circumstances the linker must not accept seeing a symbol defined more than once. However, if that symbol was declared inline, it is free to assume the definition of each is the same and ignore the rest.

Because your function is in a header file, it might get defined in more than one translation unit, so you need to break the ODR to allow your code to compile without error.


The compiler is allowed to ignore the inline keyword. If it's a Very Bad Thing to not inline this, then you should use a #define macro, or make a class with a proper constructor (since you've tagged this as C++), etc.


The behavior of the function with regard to variables "allocated on the stack" does not change, regardless of whether it is inlined or not. So, whatever stack-related concerns you have, they are equally valid (or invalid) in either case.


Most compilers only truly inline when optimisation is switched on if at all. Normally you would switch off optimisation for debugging with a source-level debugger and often such debuggers to not behave well with inlined code, making debugging of them more difficult. If the function is implemented normally, the debugger does not need to account for inlining.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜