본문 바로가기

Application-level프로그래밍

(C++) Inline function (MSDN)


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.

If you are using function inlining, you must:
Have the inline functions implemented in the header file you include.
Have inlining turned ON in the header file.
 

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