内联和良好实践

ere*_*eOn 4 c++ coding-style inline

可能重复:
何时使用内联函数和何时不使用它?

我已经看到许多源代码使用与inline指令不同的语法.

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; }
}
Run Code Online (Sandbox Code Playgroud)

我没有找到关于使用的"官方"指南inline:我只知道这inline只是编译器的一个提示,它强制执行内部链接.我不太了解它.

这是我的问题:

  • (1)良好做法?
  • 在(2)中,inline总是需要指令吗?(我的猜测是"不",但我无法解释原因).什么时候需要?
  • (3)似乎是最常用的语法.它有什么问题或者我也应该使用它吗?
  • 有没有其他用途(语法)inline我不知道?

CB *_*ley 11

不,不!inline只是对编译器的提示,它不会强制执行内部链接.

inline隐含在类主体中定义的函数上,因此您只需要在类外定义的函数上.当你要使用它,只有当你需要启用更改一个定义规则inline使.