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.
VC++ supports __forceinline and __declspec(noinline) directives if you think you know better than the compiler. Hint: you probably don't!
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...)
Both forms should be inlined in the exact same way. Inline is implicit for function bodies defined in a class definition.