Inline functions

时间:2023-01-18 14:22:44

Problems:      (Page 372)

There are two problems with the use of proprocessor macros in C++. The first is also with C: a macro looks like a function call, but does not 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.

There are many subtle bugs examples with MACRO in Page 372.

Inline functions:

Any function defined within a class body is automatically inline, but you can also make a non-class function inline by preceding it with the inline keyword. You must include the function body with the declaration, otherwise the compiler will treat it as an ordinar function declaration.

Inline function implementation mechanism:    (Page 377)

You will almost want to put inline definitions in a header file. When the compiler sees such a definition, it puts the function type and the function body in its symbol table. When you use the function, the compiler checks to ensure the call is correct and the return value is being used correctly, and then substitutes the function body for the function call, thus eliminating the overhead. The inline code does occupy space, but if the function is small, this can actually take less space than the code generated to do an ordinary function call.

The following rules of thumb might help:

inline function must be small;

access function can be inline function.

Limitations:              (Page 390)

There are two situations in which the compiler cannot perform inlining.

Firstyly, the compiler cannot perform inlining if the function is too complicated.

Secondly, the complier also cannot perform inlining if the address of the function is taken implicitly or explicitly.

Three special features in the C preprocessor:

stringizing        #define DEBUG(x) cout << #x " = " << x << endl

string concatenation

token pasting

#define FIELD(a) char* a##_string; in a##_size

class Record{

  FIELD(one);

  FIELD(two);

  FIELD(three);

};