Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct placement of 'inline'

Tags:

c++

Where do I put inline correctly?


test1.h:

class test1
{
    inline void method1() {}
};

test2.h:

class test2
{
    void method2();
};

inline void test2::method2() {}

test3.h:

class test3
{
    inline void method3();
};

inline void test3::method3() {}

test4.h:

class test4
{
    inline void method4();
};

test4.cpp:

void test4::method4() {}

test5.h:

class test5
{
    inline void method5();
};

test5.cpp:

inline void test5::method5() {}

test6.h:

class test6
{
    void method6();
};

test6.cpp:

inline void test6::method6() {}

test7.h:

class test7
{
    inline void method7();
};

void test7::method7() {}

(I'm used to code like in example 6, but read alot of inline and now im not sure about this anylonger) Which of these examples is the correct useage of inline, why do they differ and are they all valid?

EDIT #1: All these examples are indeed private, I didn't thought of public and protected in the first place. As stated in the comments there could occour major errors because of that.

like image 401
nonsensation Avatar asked Jan 31 '14 12:01

nonsensation


2 Answers

4, 5, and 6 are (probably) wrong: inline functions must be defined in every translation unit that uses them, so these only allow the function to be used in one translation unit. This might be acceptable for a private function that's only called by other functions defined in the same source file, but prevents the more general usage that you usually want from a function declared in a header.

The others are all equivalent: they contain at least one inline declaration, and exactly one definition, in a header so that the definition can be included anywhere it's needed. (As long as the header is properly protected against re-inclusion, to prevent multiple definitions in a single translation unit).

In the first, the inline keyword is redundant: functions defined inside class definitions are implicitly inline.

I would advise against 3 and 7, since they require changing both the declaration and the definition if you later decide that the function shouldn't be inline. That leaves 1 and 2 as my preferred options; and I'd only use 1 for very short functions to avoid cluttering the class definition.

like image 159
Mike Seymour Avatar answered Oct 04 '22 07:10

Mike Seymour


All of your examples except 4, 5 and 6 are correct, provided you don't call the function before a declaration with inline has been seen. In practice, 7 is about the only one I've seen in successful large scale projects; for local classes, defined in a source file, 1 is also used, but without the inline keyword (which is implicit here).

like image 39
James Kanze Avatar answered Oct 04 '22 08:10

James Kanze