9: Inline Functions
One of the important features C++
inherits from C is efficiency. If the efficiency of C++
were dramatically less than C, there
would be a significant contingent of programmers who couldn’t justify its
use.
In C, one of the ways to preserve
efficiency is through the use of
macros, which allow you
to make what looks like a function call without the normal
function call overhead. The
macro is implemented with the preprocessor instead of the compiler proper, and
the preprocessor replaces all macro calls directly with the macro code, so
there’s no cost involved from pushing arguments, making an
assembly-language CALL, returning arguments, and performing an assembly-language
RETURN. All the work is performed by the preprocessor, so you have the
convenience and readability of a function call but it doesn’t cost you
anything.
There are two problems with the use of
preprocessor macros in C++. The first is also true with
C: a macro looks like a function call, but doesn’t always act like one.
This can bury difficult-to-find bugs. The second problem is specific to C++: the
preprocessor has no permission to access class member data. This means
preprocessor macros cannot be used as class member functions.
To retain the efficiency of the
preprocessor macro, but to add the safety and class scoping of true functions,
C++ has the inline
function. In this chapter,
we’ll look at the problems of preprocessor macros in C++, how these
problems are solved with inline functions, and guidelines and insights on the
way inlines
work.
|