C++ Tips from Thinking in C++(4)

Posted by – November 21, 2005

This entry is continued from C++ Tips from Thinking in C++(3)


7. Inline functions. p359
Any function defined within a class body is automatically inline and the declaration and implementation must be together.
However, there are two situations in which the compiler cannot perform inlining.
First, if the function is too complicated. This depends upon the particular compiler, for example, any sort of looping is considered too complicated to expand as an inline in general. Second, the compiler also cannot perform inlining if the address of the function is taken implicitly or explicitly. If the compiler must produce an address, then it will allocate storage for the function code and use the resulting address.
Another interesting characteristic of Inline function is ‘Forward references’. If you’re imagining what the compiler is doing to implement inlines, you can confuse yourself into thinking there are more limitations than actually exist. In particular, if an inline makes a forward reference to a function that hasn’t yet been declared in the class (whether that function is inline or not), it can seem like the compiler won’t be able to handle it:

class Forward {
int i;
public:
Forward() : i(0) {}
// Call to undeclared function:
int f() const { return g() + 1; }
int g() const { return i; }
};
int main() {
Forward frwd;
frwd.f();
}

In f( ), a call is made to g( ), although g( ) has not yet been declared. This works because the language definition states that no inline functions in a class shall be evaluated until the closing brace of the class declaration.

WeChatWhatsAppEvernoteLineInstapaperFacebookTwitterGoogle+LinkedInBaidu

Leave a Reply

Your email address will not be published. Required fields are marked *