Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is function defined in class always inline?

As per some of the books, function defined(along with definition in header) in class are always inline. Is that true?

How we can create such scenario using test app?

like image 439
Swapnil Avatar asked Jan 07 '23 20:01

Swapnil


2 Answers

Functions defined within the class definition are implicitly marked inline.

[C++11: 9.3/2]: A member function may be defined (8.4) in its class definition, in which case it is an inline member function (7.1.2), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition. [..]

That is not the same as saying that they will be inlined.

The inline keyword has implications for storage duration and linkage requirements, and these must be abided by.

[C++11: 7.1.2/2]: A function declaration (8.3.5, 9.3, 11.3) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.

However, nowadays, your compiler will make the decision on whether to physically inline a function based on its own metrics, not based on the presence or absence of the inline keyword (because, nowadays, frankly the compiler knows best).

I have no idea what "test app" you have in mind, but an example of this in code is very simple:

struct T
{
   void foo() {}  // implicitly `inline`
};
like image 145
Lightness Races in Orbit Avatar answered Jan 14 '23 20:01

Lightness Races in Orbit


Yes, it is true, the member functions defined in the class are implicitly declared inline. But inline is only a suggestion you give to the compiler. The compiler could ignore it.

If you want to see what happen with different scenarios you could read the assembler

like image 40
Daniele Avatar answered Jan 14 '23 20:01

Daniele