When to Use Inline Functions
Inline functions are best used for small functions such as accessing private data members. The main purpose of these one- or two-line "accessor" functions is to return state information about objects; short functions are sensitive to the overhead of function calls. Longer functions spend proportionately less time in the calling/returning sequence and benefit less from inlining.
Example
The Point class, introduced in Function-Call Results can be optimized as follows:
// when_to_use_inline_functions.cpp
class Point
{
public:
// Define "accessor" functions as
// reference types.
unsigned& x();
unsigned& y();
private:
unsigned _x;
unsigned _y;
};
inline unsigned& Point::x()
{
return _x;
}
inline unsigned& Point::y()
{
return _y;
}
int main()
{
}
Assuming coordinate manipulation is a relatively common operation in a client of such a class, specifying the two accessor functions (x and y in the preceding example) as inline typically saves the overhead on:
Function calls (including parameter passing and placing the object's address on the stack)
Preservation of caller's stack frame
New stack-frame setup
Return-value communication
Old stack-frame restore
Return