【问题标题】:C++ Inlining - What is the "right" way [duplicate]C ++内联 - 什么是“正确”的方式[重复]
【发布时间】:2016-12-05 07:09:23
【问题描述】:

我在互联网上搜索了很多关于 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 在生成的代码方面应该是相同的,只是风格或个人意见的问题,所以不可能给出明确的答案。

标签: c++ class inlining


【解决方案1】:

1 和 2 是相同的。它完全依赖于编译器以内联方式实际调用它。如果你在类中定义了一个复杂的“内联”函数,写内联并不能保证它是内联的。因此,简而言之,它依赖于编译器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多