Search code examples
c++classinlining

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


I searched a lot for inlining in C++ on the internet but it seems that everybody prefers a different way of implementing.

My problem looks as follows:

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

As this function getI() gets called several thousand times, I think it is useful to "inline" this function. What is the best way of doing so:

// 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)

Can you give me a hint which way is the best or most performant implementation? Thanks for help :)


Solution

  • 1 and 2 are identical. It is totally dependent on the compiler to actually call it in inline way. If you define a complex "inline" function inside class, writing inline doesn't guarantee it to be inline. Hence in short it's compiler dependent.