定义:内联函数是一种内联扩展,即通过在每个函数调用的地址插入功能代码,从而节省开销来函数调用,避免跳转到一个子程序。 inline关键字类似于宏,编译器在它被称为每个地方放置了内联函数的新副本,内联函数的运行速度比正常的函数调用快,开销都省了,但是,有一个内存问题。如果一个内联函数被调用的10次,将有10个拷贝插入到代码的函数。因此,内联函数是最好的小功能,这些功能通常被称为。一个类的成员函数,如果在类定义中定义,在默认情况下(没有必要使用inline关键字),否则,该关键字是必要的。编译器可能会忽略程序员试图内联函数。
【样例】其实还是很有用的
//函数样例
inline int max(int a, int b) { return (a > b) ? a : b; } //c++ #include <iostream.h> int increment(int i); void main() { int i=0; while(i<3) { i=increment(i); cout<<"i is "<<i<<endl; } } //内联函数定义放在main()函数之后 inline int increment(int i) { i++; return i; }
【样例2,vc++的非标准用法】没人要
参考MSDN(懒得翻译了,看不懂的自己谷歌翻译)
The function or its caller is compiled with /Ob0 (the default option for debug builds).
The function and the caller use different types of exception handling (C++ exception handling in one, structured exception handling in the other).
The function has a variable argument list.
The function uses inline assembly, unless compiled with /Og, /Ox, /O1, or /O2.
The function is recursive and not accompanied by #pragma inline_recursion(on). With the pragma, recursive functions are inlined to a default depth of 16 calls. To reduce the inlining depth,
use inline_depth pragma.
The function is virtual and is called virtually. Direct calls to virtual functions can be inlined.
The program takes the address of the function and the call is made via the pointer to the function. Direct calls to functions that have had their address taken can be inlined.
The function is also marked with the naked __declspec modifier.
__forceinline is useful if:
inline or __inline is not respected by the compiler (ignored by compiler cost/benefit analyzer)
code portability is not required
inlining results in a necessary performance boost
Example of portable code:
#ifdef _MSC_VER #define INLINE __forceinline /* use __forceinline (VC++ specific) */ #else #define INLINE inline /* use standard inline */ #endif INLINE void helloworld() { /* inline function body */ }