Possible Duplicate:
When to use inline function and when not to use it ?
I have seen many source codes using different syntaxes regarding the inline directive.
namespace Foo
{
class Bar
{
public:
// 1 - inline on the declaration + implementation
inline int sum1(int a, int b) { return a + b; }
// 2 - inline on template declaration + implementation
template <typename T>
inline T sum2(T a, T b) { return a + b; }
// 3 - Nothing special on the declaration...
int sum3(int a, int b);
};
// 3 - But the inline directive goes after
// In the same namespace and still in the header file
inline int Bar::sum3(int a, int b) { return a + b; }
}
I failed to find an “official” guidelines regarding the usage of inline: I only know that I know not much about it.inline is just a hint to the compiler and that it enforces internal linkage.
Here are my questions:
- Is (1) good practice ?
- In (2), is the
inlinedirective always needed ? (My guess would be “no”, but I can’t explain why). When is it needed ? - (3) seems to be the most used syntax. Is there anything wrong with it or should I use it too ?
- Is there any other use (syntax) of
inlineI am unaware of ?
No, and no!
inlineis not just a hint to the compiler and it doesn’t enforce internal linkage.inlineis implicit on functions defined in a class body so you only need it on functions defined outside of classes. You should use it when, and only when, you need to enable the changes to the one definition rule thatinlinemakes.