Inlining C++ code

2019-03-19 05:39发布

Is there any difference to the following code:

class Foo  
{
  inline int SomeFunc() { return 42; }
  int AnotherFunc() { return 42; }
};

Will both functions gets inlined? Does inline actually make any difference? Are there any rules on when you should or shouldn't inline code? I often use the AnotherFunc syntax (accessors for example) but I rarely specify inline directly.

9条回答
孤傲高冷的网名
2楼-- · 2019-03-19 06:27

VC++ supports __forceinline and __declspec(noinline) directives if you think you know better than the compiler. Hint: you probably don't!

查看更多
爷的心禁止访问
3楼-- · 2019-03-19 06:32

Note that outside of a class, inline does something more useful in the code: by forcing (well, sort of) the C++ compiler to generate the code inline at each call to the function, it prevents multiple definitions of the same symbol (the function signature) in different translation units.

So if you inline a non-member function in a header file, and include that in multiple cpp files you don't have the linker yelling at you. If the function is too big for you to suggest inline-ing, do it the C way: declare in header, define in cpp.

This has little to do with whether the code is really inlined: it allows the style of implementation in header, as is common for short member functions.

(I imagine the compiler will be smart if it needs a non-inline rendering of the function, as it is for template functions, but...)

查看更多
戒情不戒烟
4楼-- · 2019-03-19 06:33

Both forms should be inlined in the exact same way. Inline is implicit for function bodies defined in a class definition.

查看更多
登录 后发表回答