C++ 内联 - 什么是"正确"的方式

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

本文关键字:正确 方式 内联 什么 C++      更新时间:2023-10-16

我在Internet上搜索了很多插入C 的内线,但似乎每个人都喜欢另一种实施方式。

我的问题如下:

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

由于此功能getI()被调用数千次,我认为"直列"此功能很有用。最好的方法是什么:

// 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是相同的。完全取决于编译器,以内联的方式将其调用。如果您在课堂内定义一个复杂的"内联"功能,则写入内联该功能不能保证它是内联的。因此,简而言之,它取决于编译器。