The idea of inlining code - placing the actual code of a small function at each call site - is a well known compiler optimization, which I have discussed before. This technique can provide significant performance improvements, due to the elimination of the call/return sequence. Also, stack usage is reduced. There is a possible cost in terms of increased program memory requirement.
It is reasonable to expect a good C or C++ compiler, when told to compile for speed, to perform inlining automatically. Some C compilers have extensions to give more control over this, but C++ has intrinsic support for inlining within the language …
C++ has a number of keywords that are additional to those in C. Among those is inline. This is a directive to the compiler requesting that the function is inlined. The compiler is at liberty to ignore the request, if the function is too big or inlining conflicts with optimization settings [i.e. if switches request small code instead of fast code]. The inline keyword is also implemented in many modern C compilers, as a language extension, and works in the same way.
Preparing RecommendationsBut C++ has some other inlining tricks. It is very common for functions, which are part of objects [class member functions] to be small and called with great frequency. Thus, such functions are strong contenders for inlining. They may be declared inline in the same way, using the keyword. However, there is another way to convey the inlining request to the compiler: place the actual code inside the class definition, instead of just declaring the function and defining it outside.
So, C++ has two different ways to declare a function to be inline:
class T1
{
public:
void foo()
{
}
};
class T2
{
public:
void foo();
};
inline void T2::foo()
{
}
In this code, both classes have an inline function called foo().
This begs a question: what is the difference, in terms of generated code, between these two ways to declare an inline?
Please post answers as comments or by email. Sorry, there is no prize, but I will post the result as a comment in a week or so.
Comments (↓ Add Your Own)
5 Comments on this Post
Commented on 8:40 PM, Feb 22, 2010
By Dan Smith
Commented on 10:37 PM, Feb 22, 2010
By Colin Walls
Commented on 8:11 AM, Mar 3, 2010
By Alex Solomatnikov
Commented on 2:57 AM, Nov 18, 2010
By Darren Darren
Commented on 8:21 AM, Nov 18, 2010
By Colin Walls
Add Your Comment
Please complete the following information to comment or sign in.