最近看代码常常把代码编译好看汇编结果,所以有机会更近的接触下inline。
Inline的好处,effective c++讲了一堆,当然是能用则用了。
这里就说下一些细节的东西。
inline是编译时刻嵌入的,在gcc的preprocess结果来看,inline并没有展开,在编译 时刻inline做了展开,在优化模式下,inline就像直接写入的代码一样,执行顺序会被编译器优化和上下文的代码参杂起来。
所以既然没有调用linker,那么如果inline函数的实现在编译时刻不可见就没法做到,在vc2005和gcc中都遇到undefined reference/symbol 的错误。
所以只要在同一个编译单元就可以。可以放在.h文件中,如果inline函数只在一个.cpp中使用,那么放在同一个.cpp中也是可以的,反正一个编译单元可见就行。
class InlineTest![](http://static.oschina.net/uploads/img/201203/09140710_pSCw.gif)
... {
inline void Test()![](http://static.oschina.net/uploads/img/201203/09140711_IOdJ.gif)
...{
//this will inline, but too ugly
}
} ;
class InlineTest![](http://static.oschina.net/uploads/img/201203/09140710_pSCw.gif)
... {
inline void Test();
} ![](http://static.oschina.net/uploads/img/201203/09140710_88OO.gif)
void InlineTest::Test() ![](http://static.oschina.net/uploads/img/201203/09140710_pSCw.gif)
... {
//this is better, but one change will bring too much compilation
}
InlineTest.h:![](http://static.oschina.net/uploads/img/201203/09140710_88OO.gif)
class InlineTest![](http://static.oschina.net/uploads/img/201203/09140710_pSCw.gif)
... {
inline void Test();
} ;![](http://static.oschina.net/uploads/img/201203/09140710_88OO.gif)
// ---------------------------------------------------------------------------------------------------------------------------------------
InlineTest.cpp:![](http://static.oschina.net/uploads/img/201203/09140710_88OO.gif)
void InlineTest::Test()![](http://static.oschina.net/uploads/img/201203/09140710_pSCw.gif)
... {
//this is pretty good, but have restriction, the function must be used in InlineTest.cpp, no where else.
} 原文链接: