C++ 内联 - 什么是 "right" 方式

C++ Inlining - What is the "right" way

我在网上搜索了很多有关 C++ 内联的内容,但似乎每个人都喜欢不同的实现方式。

我的问题如下:

// header-file
class Test {
    int i;
    public:
        int getI();
};
// source-file
int Test::getI() { return i; }

由于这个函数 getI() 被调用了数千次,我认为 "inline" 这个函数很有用。这样做的最佳方式是什么:

// 1) define the function within the class-definition
class Test {
    int i;
    public:
        int getI() { return i; }
};

// 2) define the function within the header-file
inline int Test::getI() { return i; } // directly located under class-definition

// 3) let the fct-definition stay in the source file and write "inline" before it (somehow this does not compile)

你能给我一个提示,哪种方式是最好的或最高效的实施方式?感谢您的帮助:)

1和2是一样的。它完全依赖于编译器以内联方式实际调用它。如果您在 class 中定义了一个复杂的 "inline" 函数,那么编写内联并不能保证它是内联的。因此,简而言之,它取决于编译器。